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)
numbers (numbers with only symbols '0' and '1', or in base 2).
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
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
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 =
1st. method: with Matlab help
We can get the decimal to binary conversion using the Matlab command 'dec2bin'. For
Matlab's answer is
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
'rem', 'num2str' and 'fliplr'.
rounds towards minus infinity.
remainder after a division.
converts numbers to strings.
flips matrix in left/right direction.
The proposed code is this:
dec_nr = 10;
i = 1;
while 2 <=
= i + 1;
= rem(dec_nr, 2);
1) = num2str(q);
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.
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
'Decimal to binary' to home
From 'Decimal to
binary' to 'Matlab Programming'