Double To Binary Representation (not using dec2bin)

40 次查看(过去 30 天)
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.

采纳的回答

Roger Stafford
Roger Stafford 2013-6-17
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);

更多回答(2 个)

Jonathan
Jonathan 2015-5-4
编辑:Jonathan 2015-5-4
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 个评论
Walter Roberson
Walter Roberson 2020-5-10
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 2022-4-27
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.

请先登录,再进行评论。


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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by