在 Java 中将十六进制转换为十进制

Converting Hexadecimal to Decimal in Java

我是 Stack Overflow 的新手,我在编写这个程序时遇到了一些问题。我的目标是计算文件的 CRC32 散列并以十六进制和十进制显示结果。计算十六进制的方法很好,但是当我尝试转换为十进制时,结果不正确。

例如 十六进制 af3f89fc returns 2147483647(错误)当它应该 return 2940176892

谁能帮忙看看这个方法?我不知道哪里出了问题。

旁注:returned 十六进制有小写字母。

public int toDecimal(String hex){
int dec = 0;
int len = hex.length();
for(int i = 0; i < len; i++){
  if(hex.charAt(i) == 'a') {
      dec += 11 * Math.pow(16, len-(i+1));
  }
  else if(hex.charAt(i) == 'b'){
      dec += 12 * Math.pow(16, len-(i+1));
  }
  else if(hex.charAt(i) == 'c'){
      dec += 13 * Math.pow(16, len-(i+1));
  }
  else if(hex.charAt(i) == 'd'){
      dec += 14 * Math.pow(16, len-(i+1));
  }
  else if(hex.charAt(i) == 'e'){
      dec += 15 * Math.pow(16, len-(i+1));
  }
  else{
      dec += Character.getNumericValue(hex.charAt(i)) * Math.pow(16, len-(i+1));
  }
}
return dec;
}

感谢任何能提供帮助的人。

2940176892 比最大可能值 int 稍大,这是您得到的答案:2147483647.

出现此值 Integer.MAX_VALUE 是因为您要将 int 之间的乘法结果相加,例如12,以及 Math.pow 的结果,即 double

您正在使用运算符 +=,根据 the JLS, Section 15.26.2,它隐式地将加法结果转换回被赋值的变量类型,在本例中是 int.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

根据原始收缩转换的规则,JLS, Section 5.1.3),大于Integer.MAX_VALUE的值被收缩为Integer.MAX_VALUE.

  1. In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:

(剪断)

  • Otherwise, one of the following two cases must be true:

a. The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

b. The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

(强调我的)

dec声明为long并将toDecimal声明为returnlong.

但是,您的字符转换也不正确。转换:

'a' -> 10
'b' -> 11
'c' -> 12
'd' -> 13
'e' -> 14
'f' -> 15 (include this case!)

那么你会得到2940176892的正确答案。