user4791235
user4791235

Reputation:

Have to convert Integer to binary

I'm writing a user-defined function to convert integers to binary. The largest number that could be converted with the function should be a binary number with 16 1 s. If a larger number is entered as d, the function should display an error message. With my code, I'm trying to add the numbers 0 or 1 to my vector x based on the remainder, then I want to reverse my final vector to display a number in binary. Here's what I have:

function [b] = bina(d)
% Bina is a function that converts integers to binary

x  = [];
y  = 2;
in = d/2;

if d >=(2^16 -1)
   fprintf('This number is too big')
else
    while in > 1
        if in >= 1
            r = rem(in,y);
            x = [x r]
        end
    end
end

end

Upvotes: 0

Views: 1884

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25242

As you insist on a loop:

x = [];
y = 2;
in = d;


if d >=(2^16 -1)
   fprintf('This number is too big')
else
   ii = 1;
   while in > 0
        r = logical(rem(in,y^ii));
        x = [r x];
        in = in - r*2^(ii-1);
        ii = ii+1;
   end
end

b = x;

You had the right ideas, but you need to update the variables in your while-loop with every iteration. This is mainly in, where you need to subtract the remainder. And just store the binary remainders in your variable x.

You can check your result with

x = double( dec2bin(d, 16) ) - 48

You could also use a for loop, by pre-calculating the number of iterations with

find( d < 2.^(1:16),1)

and then

if d >=(2^16 -1)
   fprintf('This number is too big')
else
   for ii = 1:find( d < 2.^(1:16),1)
        r = logical(rem(in,y^ii));
        x = [r x];
        in = in - r*2^(ii-1)
   end
end

Upvotes: 2

Related Questions