Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting binary string to a hexadecimal string JAVA

I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:

//the variable name of the binary string is: "binary"
int digitNumber = 1;
    int sum = 0;
    int test = binary.length()%4;
    if(test!=0) {
        binary = padLeft(binary, test);
    }
    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++;  
    }
    public static String padLeft(String s, int n) {
        return String.format("%0$"+n+"s", s);
    }//i added this for padding

the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:

http://www.wikihow.com/Convert-Binary-to-Hexadecimal

PS: I need to implement it(not using any built-in function)

like image 243
dumas Avatar asked Aug 31 '14 12:08

dumas


People also ask

How do you convert binary to hexadecimal?

Example − Convert binary number 1101010 into hexadecimal number. First convert this into decimal number: = (1101010)2 = 1x26+1x25+0x24+1x23+0x22+1x21+0x20 = 64+32+0+8+0+2+0 = (106)10 Then, convert it into hexadecimal number = (106)10 = 6x161+10x160 = (6A)16 which is answer.

How do you write hexadecimal in Java?

In Java code (as in many programming languages), hexadecimal nubmers are written by placing 0x before them. For example, 0x100 means 'the hexadecimal number 100' (=256 in decimal). Decimal values of hexadecimal digits.

Can hex convert to binary directly?

Thus, the conversion of hexadecimal to binary is very important. Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.

What does a byte look like in hex?

A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.


Video Answer


3 Answers

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 :

  1. The loop should iterate from 0 to binary.length()-1 (assuming the first character of the String represents the most significant bit).
  2. 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.
  3. sum must be reset to 0 after each hex digit you output.
  4. System.out.print(digitNumber); - here you should print sum, not digitNumber.

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.

like image 175
Eran Avatar answered Oct 15 '22 13:10

Eran


Use this for any binary string length:

String hexString = new BigInteger(binaryString, 2).toString(16);
like image 44
Benvorth Avatar answered Oct 15 '22 15:10

Benvorth


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

like image 21
Amit.D Avatar answered Oct 15 '22 13:10

Amit.D