Original project changes: fix negative integer DBC numbers having wrong values

This commit is contained in:
Carsten Schmiemann 2022-11-01 14:21:27 +01:00
parent 57e0666b47
commit fa09dc8c71
2 changed files with 18 additions and 2 deletions

View File

@ -830,8 +830,10 @@ dbcNumber dbcSignal::Decode(CAN_frame_t* msg)
if (m_value_type == DBC_VALUETYPE_UNSIGNED)
result.Cast((uint32_t)val, DBC_NUMBER_INTEGER_UNSIGNED);
else
result.Cast((uint32_t)val, DBC_NUMBER_INTEGER_SIGNED);
else {
int32_t signed_val = sign_extend<uint32_t, int32_t>((uint32_t)val, m_signal_size-1);
result.Cast(static_cast<uint32_t>(signed_val), DBC_NUMBER_INTEGER_SIGNED);
}
// Apply factor and offset
if (!(m_factor == 1))

View File

@ -338,4 +338,18 @@ double float2double(float f);
std::string idtag(const char* tag, void* instance);
#define IDTAG idtag(TAG,this)
/**
* sign_extend: Sign extend an unsigned to a signed integer of the same size.
*/
template <typename UINT, typename INT>
INT sign_extend(UINT uvalue, uint8_t signbit)
{
typedef typename std::make_unsigned<INT>::type uint_t;
uint_t newuvalue = uvalue;
if (newuvalue & (UINT(1U) << signbit)) {
newuvalue |= ~((uint_t(1U) << signbit) - 1);
}
return reinterpret_cast<INT &>(newuvalue);
}
#endif // __OVMS_UTILS_H__