- How to convert binary number to decimal in java
- Converting from binary to decimal java
- Java Binary to Decimal conversion: Custom Logic
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Binary to Decimal in Java
- Binary to Decimal Conversion
- Conversion
- Program 1: Binary to Decimal Conversion using Integer.parseInt()
- Program 2: Binary to Decimal using for loop
- Program 3: Binary to Decimal using while loop
- Program 4: Binary to Decimal using recursion
- Java program for binary to decimal conversion
- Method 1: Binary to Decimal conversion using Integer.parseInt() method
- Method 2: Conversion without using parseInt
- Recommended Posts
- Top Related Articles:
- About the Author
- Comments
How to convert binary number to decimal in java
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
Overview
A binary number is a number which is composed of digits 1 and 0 such as 110011. A decimal number is a number which is composed of digits 0 to 9 such as 130672.
It is a common requirement in computer programming to convert a binary number to decimal number and vice-versa.
In this post, we will focus on different ways in which a binary number can be converted to decimal number in java.
Logic
To convert a binary number to decimal form, its digits are multiplied by 2 raised to the power of their position in the number and the result is added.
Final sum after multiplying the digits and adding them is the equivalent decimal of the binary number.
The position of digits is calculated starting from right to left beginning with 0. Thus first digit at the right is at position 0, second digit at position 1 and so on.
For Example, if the binary number is 110011, then according to the above logic, its decimal conversion will be done as : 1 * 20 + 1 * 21 + 0 * 22 + 0 * 23 + 1 * 24 + 1 * 25 = 1 + 2 + 0 + 0 + 16 + 32 = 51
Every number belongs to a number system. Each number system has its own base or radix.
Thus every number has a base which tells us about the number system of this number.
Following are the common number systems and their base (or radix) : Binary Number System 2
Octal Number System 8
Decimal Number System 10
Hexadecimal Number System 16
Method 1 : Using repeated division
This is the implementation of above mentioned algorithm.
Read a number from the user . Iterate over the digits of the number and in each iteration multiply the digit with 2 raised to the power its position in the number.
The product of all digits when added give the decimal equivalent of the binary number.
Iteration of the digits should start from right to left and hence in each iteration, the number is operated with % (modulus operator) by 10.
% operator gives the remainder of the division which will be the rightmost digit. This digit is then multiplied by 2 raised to the power of its position by using pow() method of java.lang.Math class.
The position of digit and the sum are maintained by variables index and sum respectively.
static void methodTwo() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number"); // declare string containing binary number long binaryNumber = scanner.nextLong(); //represents the position of digits int index = 0; int sum = 0; while (binaryNumber > 0) { int rem = (int) binaryNumber % 10; binaryNumber = binaryNumber / 10; // multiply the digit by 2 raised to the power of its position // in the number int multiplier = (int) Math.pow(2, index); //add it to the previous sum of such products sum += rem * multiplier; radix++; } System.out.println("Decimal number is : " + sum); scanner.close(); }
Method 2 : Using Integer wrapper class
This is the simplest method of converting a binary number into decimal using an overloaded version of parseInt method in java.lang.Integer class which takes a String and a base (or radix) in which it should parse the String as arguments, that is, it identifies the number system of the string, and returns its decimal equivalent.
Read the number as input using Scanner class object. Since the number entered is in binary format, pass 2 as radix and it will return the decimal equivalent of the binary number.
static void methodOne() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number"); // declare string containing binary number String strBinaryNumber = scanner.nextLine(); //Pass 2 as the radix since number is in binary format int decimalNumber = Integer.parseInt(strBinaryNumber, 2); System.out.println("Binary number converted to decimal number"); System.out.println("Decimal number is : " + decimalNumber); scanner.close(); }
Method 3 : Using Character wrapper class
This method is also based on the similar logic. The only difference between the implementation is that the binary number is read as a String and converted to a char array using the toCharArray() method of java.lang.String class.
This character array is then iterated and the characters are converted to their integer equivalent values and multiplied by 2 raised to the power of their index in the array.
The index in array will be the same as the position in number – 1. That is, element at 4th position will be at 3rd index in the array.
To convert a character to its integer value, static getNumeric() method of java.lang.Character wrapper class can be used.
The product of digits with 2 raised to the power of its position when added, yield the decimal equivalent of the binary number.
static void methodThree() { Scanner scanner = new Scanner(System.in); System.out.println("Enter the number"); // declare string containing binary number String binaryNumber = scanner.nextLine(); char[] digits = binaryNumber.toCharArray(); int sum = 0; int index = 0; //reverse iterate the array since calculation is done from right to left for (int radix = digits.length - 1; radix >= 0; radix--) { char c = digits[index]; index++; int numericValue = Character.getNumericValue(c); int multiplier = (int) Math.pow(2, radix); sum += numericValue * multiplier; } System.out.println("Decimal number is : " + sum); scanner.close(); }
- Method 1 uses a built in method of java api, hence when conversion is required using inbuilt java functionality, then this method should be used.
- If a negative binary number is passed to parseInt() method then the corresponding result is also a negative number.
Example, conversion of binary -1101 will be -12. - From the above point, it becomes clear that Method 1 has the support for negative number conversion, while Methods 2 and 3 need to be modified for this.
- If the String supplied to parseInt() method is not in the format of supplied radix, then a java.lang.NumberFormatException is thrown such as passing String “543” with radix 2.
Hope you liked the different methods. There are more methods too. In case you know one, do let us know .
Converting from binary to decimal java
Java Binary to Decimal conversion: Custom Logic
We can convert binary to decimal in java using custom logic.
Decimal of 1010 is: 10 Decimal of 10101 is: 21 Decimal of 11111 is: 31
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Binary to Decimal in Java
In this tutorial, we will look at different Java programs that convert binary to decimal.
Binary to Decimal Conversion
A binary number is a number expressed in the base-2 numeral system or binary numeral system, which uses only two symbols: typically «0» (zero) and «1» (one). Each digit is referred to as a bit.
A decimal number is a number expressed in the base-10 numeral system or decimal numeral system, which uses ten symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each digit is referred to as a place value.
Conversion
Binary to decimal conversion is a simple process. We just need to multiply each digit with its corresponding power of 2 and add them all.
We can represent a binary number as a decimal system as follows:
(1010)2 = (1*23 + 0*22 + 1*21 + 0*20)10 = 1010 (1011)2 = (1*23 + 0*22 + 1*21 + 1*20)10 = 1110 (11001)2 = (1*24 + 1*23 + 0*22 + 0*21 + 1*20)10 = 2510
Program 1: Binary to Decimal Conversion using Integer.parseInt()
Integer.parseInt() method is used to convert a string to an integer. It takes two arguments, the string to be converted and the radix of the string.
The radix is the base of the number system. Here, we are converting a binary number to a decimal number. So, the radix is 2.
import java.util.Scanner; public class main < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a binary number: "); // input binary string String binary = s.nextLine(); // convert binary to decimal int decimal = Integer.parseInt(binary, 2); System.out.println(decimal); s.close(); >>
Enter a binary number: 100101 37
Program 2: Binary to Decimal using for loop
In this program, we will create a function that takes a binary number as a string and returns its decimal equivalent.
Within the function, we use a for loop to iterate through the string from the right. We multiply each digit with its corresponding power of 2 and add them all.
import java.util.Scanner; public class main < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a binary number: "); // input binary string String binary = s.nextLine(); // convert binary to decimal System.out.println(bin2dec(binary)); s.close(); >static int bin2dec(String binary) < int decimal = 0; int n = 0; for (int i = binary.length() - 1; i >= 0; i--) < // if current digit is 1 if (binary.charAt(i) == '1') < decimal += Math.pow(2, n); >n++; > return decimal; > >
Enter a binary number: 10110 22
Program 3: Binary to Decimal using while loop
Here we will use the same approach as in the previous program. But, we will use a while loop instead of a for loop.
To work with this we create a variable that keeps track of the current digit. We multiply this variable with its corresponding power of 2 and add them all.
import java.util.Scanner; public class main < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a binary number: "); // input binary string String binary = s.nextLine(); // convert binary to decimal System.out.println(bin2dec(binary)); s.close(); >static int bin2dec(String binary) < int decimal = 0; int n = 0; int index = binary.length() - 1; while (index >= 0) < // if current digit is 1 if (binary.charAt(index) == '1') < decimal += Math.pow(2, n); >n++; index--; > return decimal; > >
Enter a binary number: 10100 20
Getting binary as an integer:
You can also get binary input as an integer. In that case, you can use the following program:
import java.util.Scanner; public class main < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a binary number: "); // input binary string int binary = s.nextInt(); // convert binary to decimal System.out.println(bin2dec(binary)); s.close(); >static int bin2dec(int binary) < int decimal = 0; int n = 0; while (binary != 0) < // if current digit is 1 if (binary % 10 == 1) < decimal += Math.pow(2, n); >n++; binary /= 10; > return decimal; > >
Enter a binary number: 10100 20
Program 4: Binary to Decimal using recursion
In this program, we will use recursion to convert binary to decimal.
import java.util.Scanner; public class main < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a binary number: "); // input binary integer int binary = s.nextInt(); // convert binary to decimal System.out.println(bin2dec(binary)); s.close(); >static int bin2dec(int binary) < // base case if (binary == 0) < return 0; >return (binary % 10) + 2 * bin2dec(binary / 10); > >
Enter a binary number: 110101 53
Java program for binary to decimal conversion
There are two following ways to convert binary number to decimal number:
1) Using Integer.parseInt() method of Integer class.
2) Do conversion by writing your own logic without using any predefined methods.
Method 1: Binary to Decimal conversion using Integer.parseInt() method
The Integer.parseInt() method accepts two arguments, first argument is the string which you want to parse and the second argument is the radix. Here, we provided the radix as 2, because we are converting a binary number. The radix is the base of the number we are converting, for example: radix is 8 for octal number conversion, for hex to decimal radix 16 and so on.
import java.util.Scanner; class BinaryToDecimal < public static void main(String args[])< Scanner input = new Scanner( System.in ); System.out.print("Enter a binary number: "); String binaryString =input.nextLine(); System.out.println("Output: "+Integer.parseInt(binaryString,2)); >>
Enter a binary number: 1101 Output: 13
Method 2: Conversion without using parseInt
Here, we are not using the parseInt() method. We have created a user defined method BinaryToDecimal() , where we have written the logic for binary to decimal conversion.
public class Details < public int BinaryToDecimal(int binaryNumber)< int decimal = 0; int p = 0; while(true)< if(binaryNumber == 0)< break; >else < int temp = binaryNumber%10; decimal += temp*Math.pow(2, p); binaryNumber = binaryNumber/10; p++; >> return decimal; > public static void main(String args[]) < Details obj = new Details(); System.out.println("110 -->"+obj.BinaryToDecimal(110)); System.out.println("1101 --> "+obj.BinaryToDecimal(1101)); System.out.println("100 --> "+obj.BinaryToDecimal(100)); System.out.println("110111 --> "+obj.BinaryToDecimal(110111)); > >
110 --> 6 1101 --> 13 100 --> 4 110111 --> 55
Recommended Posts
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
I was about to know the Method 2 program .How to add or sum all the values that are displayed in console or command prompt
eg:
110 –> 6
1101 –> 13
100 –> 4
110111 –> 55 i should get the decimal value at last
I wonder how to deal with negative powers in the input.
Example if you want to convert the decimal 0.001 to binary.