[英]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.