bitset error for uint64
1 view (last 30 days)
Show older comments
Jason Palmer
on 19 Jun 2019
Commented: Jason Palmer
on 19 Jun 2019
There seems to be a problem with the bitset function for uint64. Here is a simple example:
>> d = 38124631952277504;
>> dec2bin(d)
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(d+1)
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(bitset(d,1,'uint64'))
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(bitset(d,2,'uint64'))
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(bitset(d,3,'uint64'))
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(bitset(d,4,'uint64'))
ans =
'10000111011100100010011010011000101101010100000000001000'
>> dec2bin(d+8)
ans =
'10000111011100100010011010011000101101010100000000001000'
So the bits only change successfully from 4th bit on, but fail to set fo the first three bits. This makes no sense that I can see and seems to be a serious error in Matlab.
Any help would be appreciated. Or advice on how to alert Matlab engineers.
Thanks,
Jason
0 Comments
Accepted Answer
Utkarsh Belwal
on 19 Jun 2019
Edited: Utkarsh Belwal
on 19 Jun 2019
Read the documentation of dec2bin, it is written that if number is greater than flintmax then it might not work properly. In your case d is greater than flintmax.
More Answers (1)
Steven Lord
on 19 Jun 2019
>> d = 38124631952277504;
>> dec2bin(d)
ans =
'10000111011100100010011010011000101101010100000000000000'
>> dec2bin(d+1)
ans =
'10000111011100100010011010011000101101010100000000000000'
d is a double precision array, and the distance from d to the next largest representable number is greater than 1. In fact, it's 8.
>> eps(d)
ans =
8
>> isequal(d, d+1) % returns true
If you want to work with integer data that's this large, I recommend working with integer data rather than double. Make your d variable an uint64 from the beginning. This will also allow you to see the change you're making with each bitset call without needing dec2bin.
>> du = uint64(38124631952277504)
du =
uint64
38124631952277504
>> du1 = bitset(du, 1)
du1 =
uint64
38124631952277505
>> du2 = bitset(du, 2)
du2 =
uint64
38124631952277506
>> du3 = bitset(du, 3)
du3 =
uint64
38124631952277508
>> du4 = bitset(du, 4)
du4 =
uint64
38124631952277512
If you do need to check the bits explicitly, use bitget. It's vectorized so you can get all the bits at once. If you need it as a char vector, you can combine bitget with sprintf.
bitget(du, 64:-1:1)
bitget(du1, 64:-1:1)
sprintf('%d', bitget(du4, 64:-1:1))
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!