logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Decimal to binary conversion: two methods to do it with Matlab


In this article we're going to present two methods of a decimal to binary conversion in Matlab; that is, we're going to convert decimal numbers (numbers with 10 different symbols, from '0' to '9', or in base 10) into binary numbers (numbers with only symbols '0' and '1', or in base 2).
 
First, let's understand how this works if we do it manually. Later we can automate the process.

Let's say that we need to convert the number 10 (decimal number) into a binary number.

We divide 10 by 2: the quotient is 5 and the remainder is 0 (q = 5, r = 0). The first digit for our binary number will be this remainder. 

This value will be the least significant bit (LSB) in our final value (bin = '0', so far).

We divide the previous quotient (5) by 2: the new quotient is 2 and the remainder is 1 (q = 2, r = 1). Our second digit for the binary result will be this reminder (bin = '10', so far).

We divide the previous quotient (2) by 2: the new quotient is 1 and the remainder is 0 (q = 1, r = 0). We keep this remainder and include it in the binary partial result (bin = '010', so far).

Since the latest quotient was less than 2, we know that we have finished our conversion. We take the last quotient and include it in our final binary result, and this is going to be the most significant bit (MSB) (bin = '1010', final).


1st. method: with Matlab help

We can get the decimal to binary conversion using the Matlab command 'dec2bin'. For example:

dec_nr = 10;
bin = dec2bin(dec_nr);

Matlab's answer is

bin = 1010

Note that the result is a string in Matlab, not a number.


2nd. method: our own code

To automate the process explained above, we need to explain first the commands 'floor', 'rem', 'num2str' and 'fliplr'.

'floor':  rounds towards minus infinity.
'rem': remainder after a division.
'num2str': converts numbers to strings.
'fliplr': flips matrix in left/right direction.


The proposed code is this:

dec_nr = 10;
i = 1;
q = floor(dec_nr/2);
r = rem(dec_nr, 2);
bin(i) = num2str(r(i));

while 2 <= q
    dec_nr = q;
    i = i + 1;
    q = floor(dec_nr/2);
    r = rem(dec_nr, 2);
    bin(i) = num2str(r);

end
bin(i + 1) = num2str(q);
bin = fliplr(bin)

The while-loop goes on until the quotient is less than 2. q is the quotient, r is the remainder and we keep all the remainders in variable (string) 'bin'. The last bit in our number is the MSB and it's the last quotient obtained, the one that was less than 2. 

Since the binary digits (bits) are obtained from LSB to MSB, we have to flip the array in the last step, so that we can see the appropriate order. 

 From 'Decimal to binary' to home

 From 'Decimal to binary' to 'Matlab Programming'

 Search Site
 
 
Top

Online Base Converter

Bin-to-Dec conversion

Binary-to-Hex

Hex-to-Bin

Gray Code




footer for decimal to binary page