The last byte is incorrect due to loss of precision while converting from hexadecimal to decimal numeric types. The loss of information is actually observable before packing the CAN message.
When the number is converted to decimal, the returned value is as follows:
>> inpDec = hex2dec(inp)
ans =
5.1426e+17
The "hex2dec" function converts the hexadecimal number to floating-point integer representation as mentioned in the following link:
This function might not return an exact conversion if the value of the hex string is larger than the hexadecimal equivalent of the value returned by the "flintmax" function. The "flintmax" function will give the largest integer that can be stored in this floating-point integer format as mentioned here:
Since the variable "inpDec" is a double data type, the largest integer that can be reliably represented this way is:
>> flintmax('double')
ans =
9.0072e+15
This tells us that the value of "inpDec" is larger than what can be represented in the double data type. In fact, if "inpDec" were to be converted back to hex with "dec2hex", you should receive a warning informing you of this situation:
>> dec2hex(inpDec)
Warning: At least one of the input numbers is larger than FLINTMAX. Results may be unpredictable.
ans =
'72300BDE0000000'
A better option would be to use the "hex2num" function instead, which converts a IEEE hexadecimal string to a double-precision number. Additional information on the "hex2num" function can be found here:
Using this function, there is no floating-point interpretation done by MATLAB since you are directly specifying the bytes of the 64-bit number. See the following snippet of code and note that the back-conversion retains the last byte of information correctly.
>> inp_num = hex2num(inp);
>> num2hex(inp_num)
ans =
'072300bde0000002'
Converting the number with the "uint64" function is also not reccommended, as this could cause further unintentional loss of precision. The second argument of the "pack" function accepts any numeric value, including double types, so this extra conversion step is unnecessary. The following documentation page contains some more information regarding this input argument:
Best Answer