Increase Hex2dec or dec2hex output range in Matlab

1.4k views Asked by At

I have a strange problem with hex2dec function in Matlab. I realized in 16bytes data, it omits 2 LSB bytes.

hex2dec('123123123123123A');
dec2hex(ans)
Warning: At least one of the input numbers is larger than the largest integer-valued floating-point
number (2^52). Results may be unpredictable. 
ans =
1231231231231200

I am using this in Simulink. Therefore I cannot process 16byte data. Simulink interpret this as a 14byte + '00'.

2

There are 2 answers

8
Mohsen Nosratinia On

You need to use uint64 to store that value:

A='123123123123123A';
B=bitshift(uint64(hex2dec(A(1:end-8))),32)+uint64(hex2dec(A(end-7:end)))

which returns

B =

  1310867527582290490
0
Amro On

An alternative way in MATLAB using typecast:

>> A = '123123123123123A';
>> B = typecast(uint32(hex2dec([A(9:end);A(1:8)])), 'uint64')
B =
  1310867527582290490

And the reverse in the opposite direction:

>> AA = dec2hex(typecast(B,'uint32'));
>> AA = [AA(2,:) AA(1,:)]
AA =
123123123123123A

The idea is to treat the 64-integer as two 32-bit integers.

That said, Simulink does not support int64 and uint64 types as others have already noted..