[英]Convert Hex To Byte Array in Java gives different results from C#.NET [port from C# to Java]
我正在尝试将一小段代码从C#转换为Java。 [我认为不必说我是菜鸟。 :P]
以下两个代码返回的结果不同,我不明白为什么。 谢谢你的帮助。
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
我不明白为什么会发生这种情况,如何克服它?
问题在于您将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;
}
尽管移位非常有效,但它的可读性不如简单地除以二...并且将代码拆分成多个语句使读取它的每个单独部分变得容易得多。
(我可能会用switch语句实现parseHex
,也为非十六进制数字抛出IllegalArgumentException
……)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.