convert 9.2532 decimal into binary matlab

2019-09-19 18:51发布

问题:

I use de2bi(x) but it help only for integer i want to convert for digit with point decimal into binary

de2bi(x)

convert this 9.2553 into decimal with fraction part also convert into binary format in Matlab if possible than without function file with code want output

回答1:

MATLAB, of course, already stores double values in binary using IEEE-754 binary64 format. All we have to do is somehow get MATLAB to show us the bits.

One way is to use typecast which makes MATLAB interpret a set of memory locations as a different type. In this case, we'll make MATLAB think a double is a uint64 and then send the "integer" through dec2bin. We'll have to do some decomposition on the string after that to get the actual value.

Note: This currently only works with positive values. If you need negative values too, I'll have to make some adjustments.

function binstr = double2bin(d)
   d = double(d);   % make sure the input is a double-precision float
   ieee754_d = dec2bin(typecast(d, 'uint64'),64);   % read double as uint64
   % IEEE-754 64-bit double:
   %    bit 1 (msb) = sign bit (we'll ignore this for now)
   %    bits 2-12   = exponent with bias of 1023
   %    bits 13-64  = significand with leading 1 removed (implicit)
   exponent = bin2dec(ieee754_d(2:12))-1022;   % 2^n has n+1 bits
   significand = ['1' ieee754_d(13:64)];
   if (exponent < 1)   % d < 1, so we'll need to pad with zeros
      binstr = ['0.' repmat('0',1,-exponent) significand];
   else   % d >= 1; move exponent bits to the left of binary point
      binstr = [significand(1:exponent) '.' significand(exponent+1:end)];
   end
end

Test run:

>> double2bin(9.2532)
ans = 1001.0100000011010001101101110001011101011000111000100


回答2:

Ad hoc solution:

Expand by 2^44 (to get an integer value).
Convert integer result to binary.
Reduce by 2^44 by placing "decimal" point.
(2^44 is the smallest power of 2 expansion that gives an integer result).

Code sample:

expandedRes = dec2bin(9.2553*2^44);
res = expandedRes[1:end-44, '.', end-43:end);

Result:

res =

1001.01000001010110110101011100111110101010110011