简体   繁体   English

将字符串二进制转换为十六进制

[英]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".我的字符串二进制是“1110101011111010”。 The output should be EAFA, but my output is EA7A.输出应该是EAFA,但我的输出是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.您代码中的实际问题是,在digitNumber == 9的情况下,您将digitNumber设置为 1 然后将其递增,但您不解析该数字,因此您跳过了第二个字节的第一位重新解析。

The recommended approach would be to switch to using Integer.parseInt(binary, 2) , Long.parseLong(binary, 2) or even new BigInteger(binary, 2) .推荐的方法是切换到使用Integer.parseInt(binary, 2)Long.parseLong(binary, 2)甚至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:但是,如果您想修复您的代码,您需要将digitNumber == 9的检查移动到循环的开头,并且独立于其他 if 语句,因此:

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.如果您需要一个长string ,您可以使用BigInteger将任何二进制字符串转换为十六进制。

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.使用@Bohemian♦ 所做的内置函数当然是最简单的。 But if you really need/want to do the binary conversion manually, you can change your for loop to the following:但是,如果您确实需要/想要手动进行二进制转换,则可以将for循环更改for以下内容:

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) . 1 << i等价于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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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