Binary
to decimal  Four ways to convert formats
in Matlab
In this article we're going to present four variations of a binary to
decimal conversion in Matlab; we're going to convert
binary numbers (numbers with
only symbols '0' and '1') to decimal
numbers
(numbers with 10 different symbols, from '0' to '9').
First, I'm going to show you a video explaining the general
ideas behind a base conversion. Later, I'm going to
show you the ideas to make it happen in Matlab.
As you may know, a number expressed in decimal format (the common way
to express a number, also called base 10) consists of additions of
digits raised to the different powers of 10.
For example:
1528 (base
10) means 1 x 10^{3} + 5 x 10^{2}
+ 2 x 10^{1}
+ 8 x 10^{0}
Following the same reasoning, a binary number (called to be in base 2)
consists of additions of binary digits raised to the different powers
of 2. For example:
1010
(base 2) means 1 x 2^{3}
+ 0 x 10^{2} + 1 x 10^{1}
+ 0 x 2^{0}
1st. Method: using the bin2dec function.
The 'bin2dec'
builtin function converts a binary number string to a decimal number.
Example:
bin_nr =
'110101';
dec =
bin2dec(bin_nr)
The result is dec
= 53.
2nd. Method: using a forloop.
In the event that we cannot use the bin2dec function for any reason, we
have to elaborate an alternative. In this case, we just follow the
logic explained above: every digit found in the input string is
obtained with every iteration and it is converted into a real number
(in this case the input is a string, not a number, that's why
we
use the instruction 'str2num').
bin_nr =
'110101';
dec = 0;
for i = 1 :
length(bin_nr)
dec
= dec + str2num(bin_nr(i)) *
2^(length(bin_nr)  i);
end
dec
As expected, the result
is also dec
= 53.
3rd. Method: using a whileloop.
Now, we make a small change in
the logic to work with a whileloop instead of a forloop, just for a
variation. The idea is the same, but we have to add an index to keep
track of the appropriate power of the digit to be considered. This
binary to decimal conversion also includes input from the user:
bin_nr =
input('Enter
your binary number: ', 's');
dec = 0;
i = 1;
while i <
length(bin_nr) + 1
dec
= dec + str2num(bin_nr(i)) *
2^(length(bin_nr)  i);
i
= i + 1;
end
dec
4rd. Method: using 'polyval'.
As seen in the articles about polynomials and curve fitting (see Table
of Contents), the 'polyval'
function
with arguments (p, x) returns the
value of a polynomial of degree n
evaluated at x.
The input argument p
is a vector of length n+1
whose elements are the coefficients in descending powers of the
polynomial to be evaluated. This is exactly what we need if the input
is in vector form. In other words, the expected result is:
y = p_{1}x^{n}
+ p_{2}x^{n1}
+ ... + p_{n}x + p_{n+1}
And that's achieved this way:
bin_nr =
[1 1 0 1 0 1];
dec =
polyval(bin_nr, 2)
From
'Binary to decimal' to home
From 'Binary to
decimal' to Matlab Programming

