c# - 是否有与 Python 的 unhexlify 等效的 C#?

标签 c# python binary hex

<分区>

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);
}

关于c# - 是否有与 Python 的 unhexlify 等效的 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1459006/

相关文章:

c++ - 无法将 1 和 0 的字符串写入二进制文件,C++

c# - 将 Paypal 与 wpf 应用程序中的链接集成

使用附加参数包装函数并更改输出的 Pythonic 方式

python - Pandas :无法更改列数据类型

python - 日志记录模块不写入文件

c - 尝试将二进制转换为格雷码

.Net 序列化 - 将 [Serializable] 与继承树中的自定义混合

c# - WCF 序列化异常 - NetDataContractSerializer

c# - XML序列化和反序列化与内存流

c# - 如何从 2 个单独的文本文件创建组合列表?