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

huangapple go评论69阅读模式
英文:

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++;
        }
    }
}

大家好,我正尝试将二进制字符串转换为十六进制。我的二进制字符串是 "1110101011111010"。输出应该是 "EAFA",但我的输出却是 "EA7A"。
我的代码有什么问题吗?有谁可以帮帮我吗?谢谢!

英文:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) 
{
int digitNumber=1;
int sum = 0;
String binary = &quot;1110101011111010&quot;;
String hex;
for(int i = 0; i &lt; binary.length(); i++)
{
if(digitNumber == 1)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*128;
else if (digitNumber == 2)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*64;
else if (digitNumber == 3)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*32;
else if (digitNumber == 4)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*16;
else if (digitNumber == 5)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*8;
else if (digitNumber == 6)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*4;
else if (digitNumber == 7)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*2;
else if (digitNumber == 8)
{
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*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?

答案1

得分: 1

我认为你的代码太多了。

试试这个:

String hex = Long.toHexString(Long.parseLong(binary, 2)); // 可处理最多 63 位

记住代码越多潜藏 bug 的地方就越多
英文:

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.

答案2

得分: 1

你代码中的实际问题在于,在digitNumber == 9的情况下,你将digitNumber设置为1,然后递增它,但你没有解析该数字,因此你跳过了要解析的第二字节的第一个位。

推荐的方法是改用Integer.parseInt(binary, 2)Long.parseLong(binary, 2)甚至是new BigInteger(binary, 2)

然而,如果你想修复你的代码,你需要将对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
    // 其余的if...
    digitNumber++;
}
英文:

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 &lt; binary.length(); i++) {
if (digitNumber == 9) {
digitNumber = 1;
sum=0;
}
if(digitNumber == 1)
sum += Integer.parseInt(binary.charAt(i) + &quot;&quot;)*128;
else
// rest of your if...
digitNumber++;
}

答案3

得分: 1

代码部分不要翻译,只返回翻译好的部分:

在需要处理长字符串时,你可以使用 BigInteger 将任何二进制字符串转换为十六进制。

输出:

BigInteger num = BigInteger.valueOf(Long.MAX_VALUE);
String binaryStr = num.add(num).toString(2);                // 比 long 大两倍
System.out.println(convertBinaryToHexadecimal(binaryStr));  // fffffffffffffffe

用下面的方法可以将十六进制字符串转换为二进制,并指定长度。

输出:

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

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(&quot;%0&quot; + length + &#39;d&#39;, new BigInteger(new BigInteger(hexadecimalStr, 16).toString(2)));
}

Output:

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

答案4

得分: 0

当然,使用内置函数是最简单的,就像@Bohemian♦所做的那样。但是如果您真的需要/想要手动进行二进制转换,您可以将您的for循环更改为以下内容:

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

这个循环从右到左遍历二进制字符串。1 << i 等同于 Math.pow(2, i)

英文:

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 &lt; binary.length(); i++) {
sum += Integer.parseInt(binary.charAt(binary.length() - i - 1) + &quot;&quot;) * (1 &lt;&lt; i);
}

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

答案5

得分: 0

以下是翻译好的内容:

我使用了基本方法将二进制字符串转换为十六进制请查看下面的代码

public class StringToHexaDecmal {

    // 主程序用于测试上述函数
    public static void main(String[] args) {
        String num = new String("1110101011111010");
        int decValue = binaryToDecimal(num);
        stringToHexadecimal(decValue);
    }

    // 将二进制转换为十进制的函数
    static int binaryToDecimal(String n) {
        String num = n;
        int dec_value = 0;

        // 初始化基值为1,即 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;
    }

    // 将十进制值转换为十六进制的函数
    private static void stringToHexadecimal(int no) {
        // TODO: 自动生成的方法存根
        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);
    }
}
英文:

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(&quot;1110101011111010&quot;);
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 &gt;= 0; i--) {
if (num.charAt(i) == &#39;1&#39;)
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 = &quot;&quot;;
char c;
while (no != 0) {
int rem = no % 16;
if (rem &gt; 9 &amp;&amp; rem &lt;= 15) {
c = (char)(rem + 55);
hexadecimalNo = c + hexadecimalNo;
}
if (rem &lt; 10) {
hexadecimalNo = rem + hexadecimalNo;
}
no = no / 16;
}
System.out.println(hexadecimalNo);
}
}

huangapple
  • 本文由 发表于 2020年9月27日 16:06:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64086246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定