Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

xcode - convert 9.2532 decimal into binary matlab

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...