dumas
dumas

Reputation: 219

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)

Upvotes: 17

Views: 81954

Answers (7)

sibel bayirli
sibel bayirli

Reputation: 1

private final String[] hexValues = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};

public void binaryToHexadecimal(String binary){
    String hexadecimal;
    binary  = leftPad(binary);
    System.out.println(convertBinaryToHexadecimal(binary));

}

public String convertBinaryToHexadecimal(String binary){
    String hexadecimal = "";
    int sum = 0;
    int exp = 0;
    for (int i=0; i<binary.length(); i++){
        exp = 3 - i%4;
        if((i%4)==3){
            sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
            hexadecimal = hexadecimal + hexValues[sum];
            sum = 0;
        }
        else
        {
            sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
        }
    }
    return hexadecimal;
}

public String leftPad(String binary){
    int paddingCount =  0;
    if ((binary.length()%4)>0)
        paddingCount = 4-binary.length()%4;

    while(paddingCount>0) {
        binary = "0" + binary;
        paddingCount--;
    }
    return binary;
}

Upvotes: 0

Benvorth
Benvorth

Reputation: 7722

Use this for any binary string length:

String hexString = new BigInteger(binaryString, 2).toString(16);

Upvotes: 11

Zayeed A. Chowdhury
Zayeed A. Chowdhury

Reputation: 1

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stringprocessing;

/** * * @author Zayeed Chowdhury */ public class StringProcessing {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    int index = 0;
    String bin = "0000000101100101011011100110011100000001000000000000000010101010010101100110010101100011011010010110110101100001001000000100111001100101011101000111011101101111011100100110101101110011001000000100100001000001010100110010000001001001010100110101001101010101010001010100010000100000010000010010000001010010010001010101000101010101010010010101001001000101010001000010000001010111010001010100010101001011010011000101100100100000010101000100010101010011010101000010000001000110010011110101001000100000010101000100100001000101001000000100011001001111010011000100110001001111010101110100100101001110010001110010000001000011010011110101010101001110010101000100100101000101010100110010111101000001010100100100010101000001010100110011101000100000010100000110100101101110011000010110110000101100001000000100000101011010001110110010000001000001010101000010000000000001111000000011000100110010001110100011000100110011001000000101000001001101001000000100111101001110";
    String[] hexString = new String[bin.length() / 4];
    for (int i = 0; i < bin.length() / 4; i++) {
        hexString[i] = "";
        for (int j = index; j < index + 4; j++) {
            hexString[i] += bin.charAt(j);
        }
        index += 4;
    }

    for (int i = 0; i < bin.length() / 4; i++) {
        System.out.print(hexString[i] + " ");
    }

    System.out.println("\n" + bin.length());
    String[] result = binaryToHex(hexString);

    for (int i = 0; i < result.length; i++) {
        System.out.print("" + result[i].toUpperCase());
    }
    System.out.println("");
}

public static String[] binaryToHex(String[] bin) {
    String[] result = new String[bin.length];
    for (int i = 0; i < bin.length; i++) {
        result[i] = Integer.toHexString(Integer.parseInt(bin[i], 2));
    }
    //return Integer.toHexString(Integer.parseInt(bin[0], 2));
    return result;
}

}

Upvotes: 0

user6490462
user6490462

Reputation:

By given binary number 01011011, we will convert it at first to decimal number, each number will be Math.pow() by decrementd length:

01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (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 get decimal number we have to convert it to hexa-decimal-number.

So, 91 is greater than 16. So, we have to divide by 16.

After dividing by 16, quotient is 5 and remainder is 11.

Remainder is less than 16.

Hexadecimal number of remainder is B.

Quotient is 5 and hexadecimal number of 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');
}

Upvotes: 0

rayan
rayan

Reputation: 1

 import java.util.*;
 public class BinaryToHexadecimal
 {
      public static void main()
      {
         Scanner sc=new Scanner(System.in);
         System.out.println("enter the binary number");
         double s=sc.nextDouble();
         int c=0;
         long s1=0;
         String z="";
         while(s>0)
         {
           s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
           s=(long)s/10;
           c++;
         }
         while(s1>0)
         {
           long j=s1%16;
           if(j==10)
           {
              z="A"+z;
           }
           else if(j==11)
           {
              z="B"+z;
           }
           else if(j==12)
           {
              z="C"+z;
           }
           else if(j==13)
           {
              z="D"+z;
           }
           else if(j==14)
           {
              z="E"+z;
           }
           else if(j==15)
           {
              z="F"+z;
           }
           else
           {
              z=j+z;
           }
           s1=s1/16;
      }
    System.out.println("The respective Hexadecimal number is : "+z);
   }
 }

Upvotes: 0

Amit.D
Amit.D

Reputation: 113

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

Upvotes: 3

Eran
Eran

Reputation: 393831

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.

Upvotes: 44

Related Questions