Converting binary string to a hexadecimal string JAVA
Use this for any binary string length:
String hexString = new BigInteger(binaryString, 2).toString(16);
If you don't have to implement that conversion yourself, you can use existing code :
int decimal = Integer.parseInt(binaryStr,2);
String hexStr = Integer.toString(decimal,16);
If you must implement it yourself, there are several problems in your code :
- The loop should iterate from 0 to binary.length()-1 (assuming the first character of the String represents the most significant bit).
- You implicitly assume that your binary String has 4*x charcters for some integer x. If that's not true, your algorithm breaks. You should left pad your String with zeroes to get a String of such length.
sum
must be reset to 0 after each hex digit you output.System.out.print(digitNumber);
- here you should printsum
, notdigitNumber
.
Here's how the mostly fixed code looks :
int digitNumber = 1;
int sum = 0;
String binary = "011110101010";
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
Output :
7AA
This will work only if the number of binary digits is divisable by 4, so you must add left 0
padding as a preliminray step.
You can try something like this.
private void bitsToHexConversion(String bitStream){
int byteLength = 4;
int bitStartPos = 0, bitPos = 0;
String hexString = "";
int sum = 0;
// pad '0' to make input bit stream multiple of 4
if(bitStream.length()%4 !=0){
int tempCnt = 0;
int tempBit = bitStream.length() % 4;
while(tempCnt < (byteLength - tempBit)){
bitStream = "0" + bitStream;
tempCnt++;
}
}
// Group 4 bits, and find Hex equivalent
while(bitStartPos < bitStream.length()){
while(bitPos < byteLength){
sum = (int) (sum + Integer.parseInt("" + bitStream.charAt(bitStream.length()- bitStartPos -1)) * Math.pow(2, bitPos)) ;
bitPos++;
bitStartPos++;
}
if(sum < 10)
hexString = Integer.toString(sum) + hexString;
else
hexString = (char) (sum + 55) + hexString;
bitPos = 0;
sum = 0;
}
System.out.println("Hex String > "+ hexString);
}
Hope this helps :D