简体   繁体   中英

Convert string binary to hexadecimal

import java.util.*;
import java.io.*;
public class Main
{
    public static void main(String[] args) 
    {
        int digitNumber=1;
        int sum = 0;
        String binary = "1110101011111010";
        String hex;
        for(int i = 0; i < binary.length(); i++)
        {
        if(digitNumber == 1)
            sum += Integer.parseInt(binary.charAt(i) + "")*128;
        else if (digitNumber == 2)
            sum += Integer.parseInt(binary.charAt(i) + "")*64;
        else if (digitNumber == 3)
            sum += Integer.parseInt(binary.charAt(i) + "")*32;
        else if (digitNumber == 4)
            sum += Integer.parseInt(binary.charAt(i) + "")*16;
        else if (digitNumber == 5)
            sum += Integer.parseInt(binary.charAt(i) + "")*8;
        else if (digitNumber == 6)
            sum += Integer.parseInt(binary.charAt(i) + "")*4;
        else if (digitNumber == 7)
            sum += Integer.parseInt(binary.charAt(i) + "")*2;
        else if (digitNumber == 8)
        {
            sum += Integer.parseInt(binary.charAt(i) + "")*1;
            hex = Integer.toString(sum,16);
            System.out.print(hex);
        }
        else if (digitNumber == 9)
        {
            digitNumber = 1;
            sum=0;
        }
        digitNumber++;
            
        }
    }
}

Hi everyone, I am trying to convert String of Binary to Hexadecimal. My string binary is "1110101011111010". The output should be EAFA, but my output is EA7A. What's wrong with my code? Can anybody help me, please?

I think you have too much code.

Try this:

String hex = Long.toHexString(Long.parseLong(binary, 2)); // handles up to 63 bits

Remember: The more code you have, the more places there are for bugs to lurk.

The actual problem in your code is that in the case of digitNumber == 9 , you set digitNumber to 1 and then increment it, but you don't parse that digit, so you're skipping the first bit of the second byte you're parsing.

The recommended approach would be to switch to using Integer.parseInt(binary, 2) , Long.parseLong(binary, 2) or even new BigInteger(binary, 2) .

However, if you want to fix your code, you need to move the check for digitNumber == 9 to the start of the loop, and independent of the other if-statements, so:

for(int i = 0; i < binary.length(); i++) {
    if (digitNumber == 9) {
        digitNumber = 1;
        sum=0;
    }

    if(digitNumber == 1)
        sum += Integer.parseInt(binary.charAt(i) + "")*128;
    else
    // rest of your if...
    digitNumber++;
}

In case you expect a long string , you can use BigInteger to convert any binary string to hexadecimal.

public static String convertBinaryToHexadecimal(String binaryStr) {
    return new BigInteger(binaryStr, 2).toString(16);
}

Output:

BigInteger num = BigInteger.valueOf(Long.MAX_VALUE);
String binaryStr = num.add(num).toString(2);                // 2 times bigger than long
System.out.println(convertBinaryToHexadecimal(binaryStr));  // fffffffffffffffe

public static String convertHexadecimalToBinary(String hexadecimalStr, int length) {
    return String.format("%0" + length + 'd', new BigInteger(new BigInteger(hexadecimalStr, 16).toString(2)));
}

Output:

String hexadecimalStr = "7B";
System.out.println(convertHexadecimalToBinary(hexadecimalStr, 8));  // 01111011

It is certainly easiest to use the built-in functions like @Bohemian♦ has done. But if you really need/want to do the binary conversion manually, you can change your for loop to the following:

for (int i = 0; i < binary.length(); i++) {
    sum += Integer.parseInt(binary.charAt(binary.length() - i - 1) + "") * (1 << i);
}

This loops through the binary string from right to left. 1 << i is equivalent to Math.pow(2, i) .

I used basic approach for convert string binary to hexadecimal, please find below:

public class StringToHexaDecmal {

    // Driver program to test above function
    public static void main(String[] args) {
        String num = new String("1110101011111010");
        int decValue = binaryToDecimal(num);
        stringToHexadecimal(decValue);
    }

    // Function to convert binary to decimal
    static int binaryToDecimal(String n) {
        String num = n;
        int dec_value = 0;

        // Initializing base value to 1,
        // i.e 2^0
        int base = 1;

        int len = num.length();
        for (int i = len - 1; i >= 0; i--) {
            if (num.charAt(i) == '1')
                dec_value += base;
            base = base * 2;
        }

        return dec_value;
    }

    // Function to convert decimal value to Hexadecimal
    private static void stringToHexadecimal(int no) {
        // TODO Auto-generated method stub
        String hexadecimalNo = "";
        char c;
        while (no != 0) {
            int rem = no % 16;
            if (rem > 9 && rem <= 15) {
                c = (char)(rem + 55);
                hexadecimalNo = c + hexadecimalNo;
            }
            if (rem < 10) {
                hexadecimalNo = rem + hexadecimalNo;
            }

            no = no / 16;

        }
        System.out.println(hexadecimalNo);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM