to Octal conversion: two methods in Matlab
In this article we're going to present two methods of a decimal to octal 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' to '7', or in base 8).
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 142 (a decimal number)
into an octal number.
We divide 142 by 8: the quotient is 17 and the remainder is 6 (q = 17,
r = 6). The first digit for our octal number will be this
value will be the least
significant digit in our final value
(assume variable oct = '6', so far).
We divide the previous quotient (17) again by 8: the new quotient is
2 and the remainder is 1 (q = 2, r = 1). Our second digit -right to
left- for the
octal result will be this reminder (variable oct = '16', so
Since the latest quotient was less than 8, we know that we have
finished our conversion. We take the last quotient and include
it in our final octal result, and this is going to be the most significant digit (oct =
'216', final result).
1st. method: with a Matlab function
We can get the decimal to octal conversion using the Matlab command
which converts a decimal integer to a base B string.
dec2base(D, B) returns the representation of D as a string
in base B. D must be a non-negative integer array
smaller than 252 and B must be an
integer between 2 and 36.
= dec2base(dec_nr, 8);
Matlab's answer is
Note that the result is a 3-character string in Matlab, it's not a
2nd. method: our own idea
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 and example is this:
i = 1;
= i + 1;
= rem(dec_nr, base);
1) = num2str(q);
The while-loop goes on
until the quotient is less than our base. q is the quotient, r is the
remainder and we keep all the remainders in string
The last digit in our conversion is the most significan digit
(MSD) and it's the last quotient
obtained, the one that was less than our base.
octal digits are obtained from least significant to
most significand digit, we have to flip the
array in the last step, so that we can see the number in the
'Decimal to octal' to Matlab home
From 'Decimal to
octal' to 'Matlab Programming'
Site/ Table of Contents