Converting decimal to binary, help!!

I'm trying to write a function that converts a string containing a number from decimal to binary (this number may include decimal points or a negative sign). I know to find, say the binary form of 25, I would simply find the remainder of 25/2, 12/2, 6/2, 3/2 and 1/2, and take those numbers and reverse them. I'm not sure how to implement this in code though. I also know that I need to split the string at the decimal point and identify its sign, which i've done below:
% function[bin]=myreal2bin(decstring)
if decstring(1)=='-'
decstring = decstring(2:end);
F = -1;
else
F = 1;
end
Ind = strfind(decstring, '.');
L = length(decstring);
if isempty(Ind)
Ind = L+1;
end
Num1 = decstring(1:Ind-1);
LN1 = length(Num1);
Num2 = decstring(Ind+1:end);
LN2 = length(Num1);
end

2 个评论

Nah, I'm frustrated because I can't understand how to write the code for this problem and I've spent hours and hours trying to figure it out. I'll change my name back soon.
In the past, has changing your name ever worked to help you to understand how to write code?

请先登录,再进行评论。

回答(1 个)

John Petersen
John Petersen 2012-11-2

0 个投票

5 个评论

I understand how it works, as you just take the remainders after dividing by 2 and then the concatenated remainder around, but im not totally sure how to write it.
@Srijohn: You cannot be sure how to write it, until you have written it. So just start to write it and ask specific questions if you get troubles.
Here's my function, I still can't get the answer though, Please help.
%
function[bin]=myreal2bin(decstring)
if decstring(1)=='-'
decstring = decstring(2:end);
F = -1;
else
F = 1;
end
Ind = strfind(decstring, '.');
L = length(decstring);
if isempty(Ind)
Ind = L+1;
end
Num1 = decstring(1:Ind-1);
LN1 = length(Num1);
Num2 = decstring(Ind+1:end);
LN2 = length(Num1);
i = 1;
q = floor(str2num(Num1));
r = rem(str2num(Num1), 2);
bin1(i) = num2str(r(i));
while 2 <= q
str2num(Num1)= q;
i = i + 1;
q = floor(str2num(Num1)/2);
r = rem(str2num(Num1), 2);
bin1(i) = num2str(r);
end
bin1(i + 1) = num2str(q);
bin1 = fliplr(bin1)
i2 = 1;
q2 = floor(str2num(Num2));
r2 = rem(str2num(Num2), 2);
bin2(i) = num2str(r2(i));
while 2 <= q
str2num(Num2)= q;
i2 = i2 + 1;
q2 = floor(str2num(Num2)/2);
r2 = rem(str2num(Num2), 2);
bin2(i2) = num2str(r2);
end
bin2(i2 + 1) = num2str(q2);
bin2 = fliplr(bin2)
bin=bin1+bin2
What are you doing with
str2num(Num1) = q;
You cannot assign a number to a function call. I think you need to assign a temp variable to it like
floatnum = str2num(Num1);
and then use this whereever you have str2num(Num1) Try that for starters.
Also, the last line
bin=bin1+bin2
will fail because these are strings. To concatenate strings, simply do
bin = [bin1, bin2];

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

标签

提问:

SB
2012-11-2

Community Treasure Hunt

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

Start Hunting!

Translated by