0

I have been dealing with an issue with MATLAB when trying to visualize the binary representation of large integers and it has really confused me. I am working on a little-endian machine and positive int64 values. Therefore, the most significant bit (MSB) is always 0. All the other bits can be 0 or 1. I noticed that when I check the binary structure of large values many bits on the least significant bits (LSB) side are 0. For instance:

>> dec2bin(4611695988848162845, 64)

ans =

    '0100000000000000000010010001000101101011011000110111100000000000' % WRONG!     
>> dec2bin(4611695988848162846, 64)

ans =

    '0100000000000000000010010001000101101011011000110111100000000000' % <--- WRONG and identical to above!

While the correct binary representation of value 4611695988848162845 should be:

Correct binary representation of 4611695988848162845:
'0100000000000000000010010001000101101011011000110111100000011101'

You can verify the correct binary structure here or use a simple C++ code to verify this. Can someone please explain to me what happens here? Doing dec2bin(int64(4611695988848162845), 64) does not seem to help either.

If_You_Say_So
  • 1,195
  • 1
  • 10
  • 25
  • In MATLAB, `4611695988848162845` is a double-precision floating-point value. Because this number is larger than 2^52, it cannot be stored exactly, lower bits are lost. – Cris Luengo Apr 16 '21 at 01:37
  • 1
    `int64(4611695988848162845)` directly creates a 64-bit integer from that string of digits. Type this at the MATLAB command prompt: `a=4611695988848162845; int64(a)` and then this: `int64(4611695988848162845)`. See the difference? In the first case `a` is a double, cast to `int64`; in the second case a `int64` is created directly. – Cris Luengo Apr 16 '21 at 05:44
  • You are right. I was focused on the `int64` part, didn't try out the `dec2bin` part. I have R2017a here, and `dec2bin` contains the statement `d = double(d);`, meaning that no matter what numeric input you give it, it is always converted to double before being converted to binary. In R2021a `dec2bin` has two code paths, one for floating-point input and one for other numeric types. – Cris Luengo Apr 16 '21 at 19:29

1 Answers1

2

'Casting' to int64 with dec2bin(int64(4611695988848162845), 64) does work on my R2020a install.

To explain why the result is incorrect for your input, look at help dec2bin:

... If D is greater than flintmax, dec2bin might not 
    return an exact representation of D. 
rinkert
  • 6,593
  • 2
  • 12
  • 31