Possible Duplicate:
How to convert hex to a byte array?
我正在 C# 中寻找一个 python 兼容的方法来将十六进制转换为二进制。我通过这样做在 Python 中反转了哈希:
import sha
import base64
import binascii
hexvalue = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
binaryval = binascii.unhexlify(hexvalue)
print base64.standard_b64encode(binaryval)
>> W6ph5Mm5Pz8GgiULbPgzG37mj9g=
到目前为止,我发现的所有各种 Hex2Binary C# 方法最终都会抛出 OverflowExceptions:
static string Hex2Binary(string hexvalue)
{
string binaryval = "";
long b = Convert.ToInt64(hexvalue, 16);
binaryval = Convert.ToString(b);
byte[] bytes = Encoding.UTF8.GetBytes(binaryval);
return Convert.ToBase64String(bytes);
}
有人知道如何生成 C# 方法来匹配 python 输出吗?
这个值对于 long(64 位)来说太大了,这就是你得到 OverflowException 的原因。
但是逐字节将十六进制转换为二进制非常容易(好吧,实际上是逐字节转换):
static string Hex2Binary(string hexvalue)
{
StringBuilder binaryval = new StringBuilder();
for(int i=0; i < hexvalue.Length; i++)
{
string byteString = hexvalue.Substring(i, 1);
byte b = Convert.ToByte(byteString, 16);
binaryval.Append(Convert.ToString(b, 2).PadLeft(4, '0'));
}
return binaryval.ToString();
}
编辑:上面的方法转换为二进制,而不是 base64。这一个转换为 base64 :
static string Hex2Base64(string hexvalue)
{
if (hexvalue.Length % 2 != 0)
hexvalue = "0" + hexvalue;
int len = hexvalue.Length / 2;
byte[] bytes = new byte[len];
for(int i = 0; i < len; i++)
{
string byteString = hexvalue.Substring(2 * i, 2);
bytes[i] = Convert.ToByte(byteString, 16);
}
return Convert.ToBase64String(bytes);
}