Double To Binary Representation (not using dec2bin)

157 views (last 30 days)
Hey guys,
I have some numbers with type double I would like to see in binary representation.
The problem with dec2bin is that it shows you the regular binary representation and not the double type representation which is sign, exponent and fraction.
Any idea how to do that?
Thanks a lot.
Assaf.

Accepted Answer

Roger Stafford
Roger Stafford on 17 Jun 2013
Many years ago I wrote a function to do what you describe for my ancient version of matlab. I called it 'binstr'. I believe the outdated 'setstr' call in it should be replaced by 'char'. The function displays a string of characters giving a minus sign for a negative input, a zero followed by a binary point, then 53 fractional binary digits, and finally a two's exponent. The 'log2' call is a crucial part of the code. You are welcome to use it. I give it exactly as I wrote it those many years ago. If you know how to interpret IEEE 754 format for double precision numbers, you can use the "format hex" to check on its accuracy.
function s = binstr(x)
if ~finite(x)|(length(x)~=1), error('x must be a finite scalar.'), end
b = (x<0); x = abs(x);
s = zeros(1,53);
[f,e] = log2(x);
for i = 1:53
f = 2*f;
d = floor(f);
f = f - d;
s(i) = d+48;
end
s = ['0.' s sprintf('*2^(%d)',e)];
if b, s = ['-' s]; end
s = setstr(s);

More Answers (2)

Jonathan
Jonathan on 4 May 2015
Edited: Jonathan on 4 May 2015
I was just about to go down this path when I discovered the typecast function. There's a good example at http://stackoverflow.com/questions/12748721/converting-a-non-integer-number-to-binary-in-matlab. Roger's code make sense if you need to support a custom floating point definition, but if it's single or double, typecast seems like the way to go.
ui = typecast(pi, 'uint64');
dec2bin(ui,64)
ans =
0100000000001001001000011111101101010100010001000010110000000000
  3 Comments
Walter Roberson
Walter Roberson on 10 May 2020
This does not work properly. When you dec2bin() a uint64, it will be converted to double. Notice how many of the bottom bits are 0.
Jonathan
Jonathan on 27 Apr 2022
ui = typecast(pi, 'uint64');
ans1 = dec2bin(ui,64);
ans2 = char('0' + bitget(ui,64:-1:1));
disp([ans1;ans2])
0100000000001001001000011111101101010100010001000010110000000000
0100000000001001001000011111101101010100010001000010110100011000
Thanks for pointing that out. I didn't realize dec2bin converts back to double first. bitget seems to work as expected in this case.

Sign in to comment.


Y.H Chen
Y.H Chen on 25 Apr 2017
I guess there is another way to do that.
>> x = pi;
>> q = quantizer('double');
>> y = num2bin(q,x)
y =
0100000000001001001000011111101101010100010001000010110100011000

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!