Using the given binary number 01011011 we first convert it to a decimal number, each number will be Math.pow() along the decrement length:
(1 Γ 2 (4)) + (1 Γ 2 (3)) + (0 Γ 2 (2)) + (1 Γ 2 (1)) + (1 Γ 2 (0))= (0 Γ 128) + (1 Γ 64) + (0 Γ 32) + (1 Γ 16) + (1 Γ 8) + (0 Γ 4) + (1 Γ 2) + (1 Γ 1)
= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1
= 91 (decimal form of binary number)
Now after receiving the decimal number, we must convert it to a hexadecimal number.
So 91 is over 16. So we have to divide by 16.
After dividing by 16, the coefficient is 5, and the remainder is 11.
The remainder is less than 16.
The hexadecimal number of the remainder is B.
The coefficient is 5, and the hexadecimal number of the remainder is B.
That is, 91 = 16 Γ 5 +11 = B
5 = 16 Γ 0 + 5 = 5
= 5B
Implementation:
String hexValue = binaryToHex(binaryValue); //Display result System.out.println(hexValue); private static String binaryToHex(String binary) { int decimalValue = 0; int length = binary.length() - 1; for (int i = 0; i < binary.length(); i++) { decimalValue += Integer.parseInt(binary.charAt(i) + "") * Math.pow(2, length); length--; } return decimalToHex(decimalValue); } private static String decimalToHex(int decimal){ String hex = ""; while (decimal != 0){ int hexValue = decimal % 16; hex = toHexChar(hexValue) + hex; decimal = decimal / 16; } return hex; } private static char toHexChar(int hexValue) { if (hexValue <= 9 && hexValue >= 0) return (char)(hexValue + '0'); else return (char)(hexValue - 10 + 'A'); }
user6490462
source share