user4791235
user4791235

Reputation:

MATLAB Trouble- Error help- Converting integer to binary

How do I fix this? I'm writing a program to convert integers to binary, and I Keep getting an error saying: bina(100) "Error using idivide>idivide_check (line 65) At least one argument must belong to an integer class.

 Error in idivide (line 41)
 idivide_check(a,b);

 Error in bina (line 15)
       d = idivide(d,2);"

Here's my code:

 function [n] = Bina(d)
% bina is a function that converts integers to binary
% Week 11, Question 18

   n = [];
   if d >=(2^16 -1)       
       fprintf('This number is too big')   
   else
       while d ~= 0
           r=rem(d,2);
           n=[r n];
           d = idivide(d,2);
       end
   end
end

%bina(100)
%bina(1002)
%bina(52601)
%bina(200090)

Upvotes: 2

Views: 1201

Answers (1)

rayryeng
rayryeng

Reputation: 104484

When you are putting in the number into your function, MATLAB automatically casts the result to double. idivide requires an integer. As such, you need to do a cast to an integer type before converting. Things like uint8, int8, uint16, int16 etc. will help. The u stands for unsigned which means that all of your numbers are positive, including 0. Without the u, these are signed data types and that means your integers can have negative values. It looks like you only want unsigned data types from your code, so use any of the u variants. Also, your code is checking of u >= 2^16 - 1, and so let's use uint32 to be sure. Because you're using unsigned data types, you also want to include 2^16 - 1. That means that the least significant 16 bits are all set to 1, and since your code (presumably) looks at only the least significant 16 bits, then simply do u > 2^16 - 1.

In any case, just do this when calling Bina in the command prompt:

>> Bina(uint32(100))
>> Bina(uint32(1002))
...
...

However, if you want to avoid doing this outside of the function, you can place this casting inside your function to hide this and to make calling simpler... so something like this:

 function [n] = Bina(d)
% bina is a function that converts integers to binary
% Week 11, Question 18

   %//******** Change
   d = uint32(d);

   n = [];
   if d >(2^16 -1) %// Change
       fprintf('This number is too big')    
   else
       while d ~= 0
           r=rem(d,2);
           n=[r n];
           d = idivide(d,2);
       end
   end
end

Now, you can go ahead and do this in the command prompt:

>> Bina(100)
>> Bina(1002)
...
...

Upvotes: 2

Related Questions