16

我也想将我的二进制(在字符串中)转换为十六进制字符串,这只是一个程序片段,因为该程序只是另一个更大程序的一部分:

//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

问题是我不知道填充是否有效,但我确信这个程序返回错误的二进制字符串的十六进制转换我正在尝试这样做:

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

PS:我需要实现它(不使用任何内置函数)

4

7 回答 7

41

如果您不必自己实现该转换,则可以使用现有代码:

int decimal = Integer.parseInt(binaryStr,2);
String hexStr = Integer.toString(decimal,16);

如果您必须自己实现它,那么您的代码中有几个问题:

  1. 循环应该从 0 迭代到 binary.length()-1 (假设字符串的第一个字符代表最高有效位)。
  2. 您隐含地假设您的二进制字符串对于某个整数 x 有 4*x 个字符。如果这不是真的,那么您的算法就会中断。你应该用零填充你的字符串以获得这样长度的字符串。
  3. sum必须在输出每个十六进制数字后重置为 0。
  4. System.out.print(digitNumber);- 在这里你应该打印sum,而不是digitNumber

以下是大部分固定代码的外观:

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

输出 :

7AA

这仅在二进制位数可被 4 整除时才有效,因此您必须添加左0填充作为 preliminray 步骤。

于 2014-08-31T12:45:07.337 回答
6

将此用于任何二进制字符串长度:

String hexString = new BigInteger(binaryString, 2).toString(16);
于 2018-11-19T04:53:43.810 回答
3

你可以尝试这样的事情。

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

希望这会有所帮助:D

于 2017-01-27T05:05:18.830 回答
0
 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);
   }
 }
于 2017-11-01T06:09:45.257 回答
0

通过给定的二进制数01011011,我们首先将其转换为十进制数,每个数Math.pow()的长度将递减:

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(二进制数的十进制形式)

现在得到十进制数后,我们必须将其转换为十六进制数。

所以,91 大于 16。所以,我们必须除以 16。

除以 16 后,商为 5,余数为 11。

余数小于 16。

余数的十六进制数为 B。

商是 5,余数的十六进制数是 B。

也就是说,91 = 16 × 5 +11 = B

5 = 16 × 0 + 5 = 5

= 5B

执行:

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');
}
于 2017-11-16T05:15:20.023 回答
0

/* * 要更改此许可证头,请在项目属性中选择许可证头。* 要更改此模板文件,请选择工具 | 模板 * 并在编辑器中打开模板。*/ 包字符串处理;

/** * * @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;
}

}

于 2018-09-23T06:57:43.843 回答
0

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;
}
于 2019-06-11T21:02:00.193 回答