0

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
11
  • 2
    how about using de2bi: mathworks.com/help/comm/ref/de2bi.html Commented Apr 15, 2015 at 10:08
  • 1
    @m.s. That requires communications toolbox that many might not have. Commented Apr 15, 2015 at 10:13
  • 1
    is this homework? Otherwise look at dec2bin in octave. Commented Apr 15, 2015 at 10:14
  • 2
    possible duplicate of Decimal to binary as double type array, not string Commented Apr 15, 2015 at 10:16
  • 1
    you are not updating the variable in in the while loop, that will be an infinite loop. Commented Apr 15, 2015 at 10:24

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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