Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 26197

# MATLAB- decimal to binary convert.....?

Hi,

I need to write a program that converts a positive decimal number to a binary string.
I have managed to do this for numbers smaller than 64, but after that matlab turns to scientific notation as I am effectively adding 1, 10, 100, 1000, 10000, etc. at 64 it should read 1000000 instead it gives 1e+006.

The code I have for this is:

clear

clc

num=input('Enter a  positive number: ');
num2=num;

while (num<0)
clc
fprintf('Invalid entry!\n');
a=input('Enter a positive number: ');
end

a=1;
c=num;
d=0;

while (c>=1)
b=rem(c,2);
c=c/2;
c=floor(c);
d=d+(b*a);
a=a*10;
end

lsb=rem(num,2);
msb=b;

fprintf('\n\n%g is written %g in binary form.\n\n',num2,d)
fprintf('The least-significant bit is %g\n\n',lsb)
fprintf('The most-significant bit is %g\n\n',msb)

____________________________________________

I have also managed to get it to display the binary number in reverse:

clear

clc

num=input('Enter a  positive number: ');
num2=num;

while (num<0)
clc
fprintf('Invalid entry!\n');
a=input('Enter a positive number: ');
end

fprintf('\n\n%g is written ',num2)

c=num;
d=0;

while (c>=1)
b=rem(c,2);
c=c/2;
c=floor(c);
fprintf('%g',b)
end

lsb=rem(num,2);
msb=b;

fprintf(' in binary form.\n\n')
fprintf('The least-significant bit is %g\n\n',lsb)
fprintf('The most-significant bit is %g\n\n\n',msb)

__________________________________________________

I hope that someone is able to help.

P.S. i cant just use the dec2bin command in matlab.

Comments in code would be appreciated.

Cheers

Simon Lee
0
fat_mike_
• 2
1 Solution

Commented:
hello,
you are creating integer in decimal format assuming it is binary format - this is wrong
in matlab - long integer can be up to 32 bit's long after that is will be treated as double

anyway, you need to add bits to string , not to integer

here is a working example for you,
it is not optimized at all - but it produces wat you want

clear
clc
num=input('Enter a  positive number: ');
num2=num;
while (num<0)
clc
fprintf('Invalid entry!\n');
a=input('Enter a positive number: ');
end
a=1;
c=num;
d='';
while (c>=1)
b=rem(c,2);
c=c/2;
c=floor(c);
d=[d char((b)+'0')];
%a=a*10;
end

lsb=rem(num,2);
msb=b;

fprintf('\n\n%g is written %s in binary form.\n\n',num2,d)
fprintf('The least-significant bit is %g\n\n',lsb)
fprintf('The most-significant bit is %g\n\n',msb)
0

Commented:
typo:
d=[d char((b)+'0')];

should be changed to :

d=[char(b+'0') d];
0

Commented:
fat_mike_: