0

I have a 64bits number which must be split in 4 numbers of 16bits each. I'm currently using this form:

temp(ii) = fread(fd,1,'*uint64');
A(ii,1) = bitand(bitshift(temp(ii),-48),hex2dec('FFFF'));
A(ii,2) = bitand(bitshift(temp(ii),-32),hex2dec('FFFF'));
A(ii,3) = bitand(bitshift(temp(ii),-16),hex2dec('FFFF'));
A(ii,4) = bitand(temp(ii),hex2dec('FFFF'));

Everyone is correct but the last one. If you take this number 63614152207040708 the last 16bits give 196. Matlab gives me 192. If I cast the value with uint16() or with cast(63614152207040708, 'uint16') the result is 65535.

1 Answer 1

2

Matlab does not overflow operations on integral types, it just saturates the value at the minimum or maximum level. So uint16(63614152207040708) will always return the max uint16 value (=65535).

Regarding the byte separation, look at the typecast documentation. It can help you avoid painful manual bit manipulations:

a = uint64(63614152207040708) ;

typecast( a ,'uint16')
ans =
    196    253    188    226

Just watch the endianess or use fliplr if you want to reverse it:

>> fliplr( typecast( a ,'uint16') )
ans =
    226    188    253    196

note: also be careful that by default Matlab cast every number not explicitly typed into double (64 bit float) so cast(63614152207040708, 'uint16') is different than cast(uint64(63614152207040708), 'uint16'). The result is not different here because you are over the max but it can make a difference with other values. For example with your code:

a = 63614152207040708 ; %// this is cast by default as double
A(1) = bitand(bitshift(a,-48),hex2dec('FFFF'));
A(2) = bitand(bitshift(a,-32),hex2dec('FFFF'));
A(3) = bitand(bitshift(a,-16),hex2dec('FFFF'));
A(4) = bitand(a,hex2dec('FFFF'));
A =
   226   188   253   192

is different than :

a = uint64(63614152207040708) ; %// make sure we give Matlab a uint64
A(1) = bitand(bitshift(a,-48),hex2dec('FFFF'));
A(2) = bitand(bitshift(a,-32),hex2dec('FFFF'));
A(3) = bitand(bitshift(a,-16),hex2dec('FFFF'));
A(4) = bitand(a,hex2dec('FFFF'));
A
A =
   226   188   253   196

I see you are using the right fread precision specifier to read uint64, but make sure your temp array is also defined as uint64 or the value you read is converted to double as soon as it's assigned to temp(ii).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.