Negative floats to Binary
3 views (last 30 days)
Show older comments
João Fernandes
on 2 Dec 2018
Commented: Mervat Zarour
on 25 Feb 2020
I have a matrix of 1 column with floats between -1 and 1. Something like [0.245 -0.942 0.424 -0.543]. I want to convert each number to binary in two's complement form. I've seen dec2bin only works for positive intergers. Any suggestions?
0 Comments
Accepted Answer
John D'Errico
on 2 Dec 2018
Edited: John D'Errico
on 2 Dec 2018
Just extract the bits. I'll get you started, like this.
X = -0.942;
hex = sprintf('%bx',X)
hex =
'bfee24dd2f1a9fbe'
The sign bit is bit #1. Bits #2-12 are the exponent, offset by 1023. So convert the exponent bits to an 11 bit integer between 0 and 2047. bin2dec can do that. Then subtract 1023 to write it as a power of 2.
But what you are asking for is the mantissa, in twos complement form. Just extract bits #13-64. This hack (extracted from some code I once wrote) should work:
tablout = dec2bin(0:15);
tablin = transpose('0123456789abcdef');
% ismember does the work here
[~,hexind] = ismember(hex,tablin);
Xbin = tablout(hexind,:);
Xbin = reshape(Xbin',64,[])';
Xbin
Xbin =
'1011111111101110001001001101110100101111000110101001111110111110'
You need to be a little careful in representing de-normal numbers (sometimes called subnormals.) For example:
realmin/2^20
ans =
2.12199579096527e-314
is a denormal number, represented as a double. But that is not your real question, which the code I gave should help you to solve. You can recognize a denormal because the exponent you would get will be -1023.
(I need to get around to posting num2bin one day.)
4 Comments
James Tursa
on 3 Dec 2018
I don't understand what "two's complement" has to do with any of this, given that the underlying values are floating point and not integers.
More Answers (0)
See Also
Categories
Find more on Logical 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!