0

When I try and convert a decimal number such as 1.571 into binary, I get 0 for all values that are not integers. Is there a way to display a fractional number in binary in MATLAB?

here is an excerpt of my code:

%The region between 0 and 2*pi is split up into 40 sections
N=20;
%The step is an the incrementation amount of the calculated sin
step= (2*pi)/40
%Cycle through and calculate the sin at each step
for i=1:N
    C_r(i) =  sin(step*i)
end

for i = 1 : N
    str_r = dec2bin(C_r(i),24);
end

2 Answers 2

4

You could convert your doubles to uint64 using typecast and use dec2bin then:

ui = typecast(pi, 'uint64');
dec2bin(ui)
ans =

100000000001001001000011111101101010100010001000010110000000000

typecast changes how you view your data, without any actual type conversion. So you will get the raw double as an unsigned 64 bit integer. Now you will have to decode it yourself, according to IEEE Standard 754.

1
  • Note that according to the documentation of dec2bin it's only possible to give an exact binary representation for ui up to 2^52.
    – Matt
    Feb 20, 2016 at 19:18
0

There is no one right answer on how to represent a fractional number in binary. double-precision floating point is one, see angainor's answer if this is the binary string you want. Other choices are single-precision floating point, or some form of fixed point. In fixed point, you essentially encode a scaled version of the number as an integer.

In any case, the consumer of the data needs to agree on the exact format before the binary string will make any sense. What is the use case for your binary string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.