Java Hexadecimal to Binary ConversionIn programming, converting one type to/ from a type is a crucial task. Sometimes we require, conversion from one type to another type. In the Java conversion section, we have discoed various types of conversions. In this section, we can discuss how to convert hexadecimal into binary. Hexadecimal NumberAs the name suggests Hexadecimal number comprises 16 entities with 10 digits (0-9) that represent the first 10 hexadecimal numbers and the rest six entities represented by A to F (represented by the numbers 10 to 15). Note that the lowest number in the hexadecimal system is 0 and the highest is 15 represented by F. Its base is 16. Hexadecimal to Binary ConversionIn order to convert any hexadecimal number to its binary equivalent, we must follow the steps given below:
The following table describes the hexadecimal number and corresponding binary equivalent.
Let's understand it through an example. ExampleSuppose, we have to convert AFB2 into binary equivalent. Let's take a look at the table given below, which shows us the conversion of the above hexadecimal number to its binary equivalent.
From the above figure, we have four 4-bit binary equivalents, the first one is 1010, the second one is 1111, the third one is 1011, and the fourth one is 0010. On combining all four 4-bit binary numbers, we get 101010111100010. Therefore, (AFB2)16 = (101010111100010)2. Java Program to Convert Binary to HexadecimalHexadecimalToBinary1.java Output: Enter the number: ab6da Binary Value is: 10101011011011011010 Let's see another approach. Using Switch CaseHexadecimalToBinary2.java Output: Enter the Hexadecimal Number: 2da Equivalent Binary Value = 001011011010 Let's see another approach. In this approach, first, we have initialized a constant LONG_BITS as 8. It defines the 8-bit long binary number. After that, we have defined a method conversion(). In this method, we have invoked Integer.parseInt() method. Syntax: The method accepts a string that contains the integer representation to be parsed and a radix (to be used while parsing s). It returns the integer represented by the string argument in the specified radix. It throws NumberFormatException If the string does not contain a parsable int. Another method that we have invoked is Integer toBinaryString() method Syntax: The method accepts an integer to be converted to a string. It returns a string representation of the integer argument as an unsigned integer in base 2. HexadecimalToBinary3.java Output: 11 = 00010001 AD = 10101101 F4 = 11110100 BA = 10111010 AA = 10101010 AA = 10101010 13 = 00010011 01 = 00000001 02 = 00000010 03 = 00000011 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India