I want to write a Matlab function that will convert a decimal number into a binary number.

Hi,
I am struggling to write a Matlab function that will convert a decimal number into a binary number with variables type double.
The function should also work for non-integer numbers. dec2bin doesn't work since it is only for integers.
I would be really happy if someone can help me with this! Thanks!

 Accepted Answer

This is a function I wrote for my own edification. Perhaps you can make use of it. It converts a single scalar 'double' to a string of 53 binary digits, including a binary (decimal) point, a sign, and an exponent of 2. This representation is precise, giving exactly what is contained in the number as stored in its internal IEEE 754 format.
[corrected]
function s = binstr(x)
if ~isfinite(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 = char(s);
return

8 Comments

If I remember correctly, you helped write IEEE 754!
its not working. it gives the following error:
Error in binstr (line 2)
@Star: Well, I was a member of the “Floating-Point Working Group” Subcommittee that worked on IEEE 754, However, W. Kahan of UC Berkeley and his students had already done almost all the real planning. We of the subcommittee mostly listened, questioned, occasionally objected, and then approved.
@Hope: What does the error say? Have you figured a way to correct it? The aim is to allow only finite, single scalar entries.
it says
Undefined function or variable 'finite'.
Error in binstr (line 2) if ~finite(x)|(length(x)~=1), error('x must be a finite scalar.'),end
no, i haven't figured out how to correct it
According to your error message, you still haven't changed 'finite' to 'isfinite'. I've made that change in the answer I gave some time ago.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Asked:

H
H
on 26 Oct 2017

Commented:

on 11 Nov 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!