【发布时间】:2013-09-13 00:43:22
【问题描述】:
第一篇文章在这里。我有一个从十六进制转换为十进制的任务,包括其他转换,但这个让我很难过......
所以我需要转换的十六进制值是 12345678、2A3DF8A7、00FF00FF。 00FF00FF 工作正常,这是给我带来麻烦的数值。
我知道你应该将数字乘以 16^n,但由于某种原因,我得到的值太高了,即使我认为我做得对。显然不是,因为它不起作用。帮助将不胜感激!
我的代码在过去的一个小时里一直在改变,但问题是最后一个“else”。
public void toDec()
{
dec = 0;
for (int j = 0, i = 7; j < hex.length(); j++){
if (hex.charAt(j) == 'A') {
dec += (10 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == 'B') {
dec += (11 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == 'C') {
dec += (12 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == 'D') {
dec += (13 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == 'E') {
dec += (14 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == 'F') {
dec += (15 * (int)Math.pow(16, i));
}
else if (hex.charAt(j) == '0') {
dec = dec;
}
else {
dec += ((int)hex.charAt(j)) * ((int)Math.pow(16, i));
}
i--;
}
}
【问题讨论】:
-
只是一个评论。您可以通过将
i变量替换为hex.length() - 1 - j来摆脱它。使其也适用于长于或短于 8 位的十六进制值... -
如果只是 8 位数字,
Math.pow(16, i)可以简单地为1 << i * 4,因为 16 是 2 的幂,位移就可以了。