我正在尝试将一小段代码从C#转换为Java。 [我想不要说我是一个菜鸟。 :P]
以下两个代码的回复方式不同,我不明白为什么。谢谢你的帮助。
P.S。:我已经检查了问题here,但答案并没有解决我的问题。
public class Test
{
private static sbyte[] HexToByte(string hex)
{
if (hex.Length % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");
sbyte[] arr = new sbyte[hex.Length >> 1];
int l = hex.Length;
for (int i = 0; i < (l >> 1); ++i)
{
arr[i] = (sbyte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
private static int GetHexVal(char hex)
{
int val = (int)hex;
return val - (val < 58 ? 48 : 55);
}
public static void Main()
{
Console.WriteLine(HexToByte("EE")[0]);
}
}
输出:-18
class Test
{
private static int GetHexVal(char hex)
{
int val = (int)hex;
return val - (val < 58 ? 48 : 55);
}
private static byte[] HexToByte(String hex) throws Exception {
if (hex.length() % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.length() >> 1];
int l = hex.length();
for (int i = 0; i < (l >> 1); ++i)
{
arr[i] = (byte)((GetHexVal((char)(hex.charAt(i << 1) << 4)) + (GetHexVal(hex.charAt((i << 1) + 1)))));
}
return arr;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println((HexToByte("EE")[0]));
}
}
输出:39
我不明白为什么会发生这种情况以及克服它的方法是什么?
答案 0 :(得分:2)
问题在于您对Java代码中的第一个字符进行包围。这是您的代码:
GetHexVal((char)(hex.charAt(i << 1) << 4))
获得角色,转移,然后调用GetHexVal
。您想要转移结果:
// Unnecessary cast removed
GetHexVal(hex.charAt(i << 1)) << 4
如果您使代码更简单,这将更容易看到。我会把它写成:
private static byte[] HexToByte(String hex) {
if (hex.length() % 2 == 1) {
throw new IllegalArgumentException("...");
}
byte[] arr = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2)
{
int highNybble = parseHex(hex.charAt(i));
int lowNybble = parseHex(hex.charAt(i + 1));
arr[i / 2] = (byte) ((highNybble << 4) + lowNybble);
}
return arr;
}
虽然比特移位非常有效,但它不像可读那么简单地除以2 ......并且将代码分割成多个语句使得阅读每个单独的部分变得更加容易它的。
(我可能会用switch语句实现parseHex
,也为非十六进制数字抛出IllegalArgumentException
...)