A Binary Number System is composed of two symbols : 0’s (zeroes) and 1’s (ones), which represent low or Off and high or On state respectively in digital electronics. It is primarily a number system with the base-2 and is extensively used in computer science as well. All the data is stored in the binary symbols in computers which are also called bits. The Binary System derives its name from the fact that it is composed of just two symbols. A Binary Number can also be thought of as a string of just 0’s and 1’s.
An Octal Number System comprises if eight digits ranging from 0 to 7. It derives its name from the fact that it consists of eight digits (hence Oct) which means eight. It is an 8-base number system and can be formulated by grouping the bits in a binary number in groups of three and calculating the corresponding value of each group as a single digit in the resultant Octal Number.
Input : 100100 Output: 44 Input : 1100001 Output : 141
In this article, we are going to explore 2 methods to convert a Binary Number to an Octal Number. These methods are as follows :
- Using the built-in toOctalString() method in Java
- Converting the binary number to a decimal number which is further converted to the corresponding Octal number.
Using this approach, we first convert a binary number to an Integer and then using the toOctalString() built-in method of java convert it into a string of octal numbers. This string is then converted to an Integer again.
public static String toOctalString(int num)
Parameters: The method accepts a single parameter num of integer type which is required to be converted to a string.
Return Value: The function returns a string representation of the integer argument as an unsigned integer in base 8.
- Convert the binary number into a decimal number.
- Convert this decimal number to a string of octal number using toOctalString() method.
- Convert this string again to an Integer.
Using this approach, we first convert the binary number to a decimal number. We then convert this decimal number to an octal number by continuously extracting the remainder and dividing by 8.
- Convert the binary number to a decimal number.
- Now, for this converted decimal number, run a while loop till this number becomes 0.
- In every iteration of the loop, get the remainder by dividing the number by 8.
- Multiply this remainder with increasing powers of 10.
- Finally divide the original number by 8.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.