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
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);
댓글 수: 0
추가 답변 (2개)
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
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
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
2017년 4월 25일
I guess there is another way to do that.
>> x = pi;
>> q = quantizer('double');
>> y = num2bin(q,x)
y =
0100000000001001001000011111101101010100010001000010110100011000
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!