【问题标题】:Python-like Byte Array String representation in C#C# 中的类 Python 字节数组字符串表示
【发布时间】:2015-06-09 01:04:04
【问题描述】:

这是我用来获取此字符串表示的方法:

    public static string ByteArrayToString(byte[] ba, string prefix)
    {
        StringBuilder hex = new StringBuilder(ba.Length * 2);
        foreach (byte b in ba)
        {
            if (prefix != null)
            {
                hex.Append(prefix);
            }
            hex.AppendFormat("{0:x2}", b);
        }
        return hex.ToString();
    }

这是一个字节数组 (ByteArrayToString(arr, "\\x")) 的示例字符串表示形式:

\x00\x00\x00\x80\xca\x26\xff\x56\xbf\xbf\x49\x5b\x94\xed\x94\x6e\xbb\x7a\xd0\x9d
\xa0\x72\xe5\xd2\x96\x31\x85\x41\x78\x1c\xc9\x95\xaf\x79\x62\xc4\xc2\x8e\xa9\xaf
\x08\x22\xde\x22\x48\x65\xda\x1d\xca\x12\x99\x42\xb3\x56\xa7\x99\xca\x27\x7b\x2b
\x45\x77\x14\x5b\xe1\x75\x04\x3d\xdb\x68\x45\x46\x72\x61\x20\xa9\xa2\xd9\x50\xd0
\x63\x9b\x4e\x7b\xa4\xa4\x48\xd7\xa9\x01\xd1\x8a\x69\x78\x6c\x79\xa8\x84\x39\x42
\x32\xb3\xb1\x1f\x04\x4d\x06\xca\x2c\xd5\xa0\x45\x8d\x10\x44\xd5\x73\xdf\x89\x0c
\x25\x1d\xcf\xfc\xb8\x07\x6b\x1f\xfa\xae\x67\xf9\x00\x00\x00\x03\x01\x00\x01

这是我想要的表示(这是 Python 的,忽略不同的换行位置,这都在一行上):

\x00\x00\x00\x80\xca&\xffV\xbf\xbfI[\x94\xed\x94n\xbbz\xd0\x9d\xa0r\xe5\xd2\x961
\x85Ax\x1c\xc9\x95\xafyb\xc4\xc2\x8e\xa9\xaf\x08"\xde"He\xda\x1d\xca\x12\x99B\xb
3V\xa7\x99\xca\'{+Ew\x14[\xe1u\x04=\xdbhEFra \xa9\xa2\xd9P\xd0c\x9bN{\xa4\xa4H\x
d7\xa9\x01\xd1\x8aixly\xa8\x849B2\xb3\xb1\x1f\x04M\x06\xca,\xd5\xa0E\x8d\x10D\xd
5s\xdf\x89\x0c%\x1d\xcf\xfc\xb8\x07k\x1f\xfa\xaeg\xf9\x00\x00\x00\x03\x01\x00\x0
1

Python 表示似乎将(十进制)32 和 126 之间的字节转换为它们的 ASCII 表示,而不是统一转义所有字节。如何让 C# 版本产生相同的字符串输出?我依赖于这个字符串输出的哈希值,所以它们需要完全相同。

【问题讨论】:

  • 我想从一个字节数组中产生一个字符串,而不是把一个字符串变成一个字节数组

标签: c# escaping bytearray ascii


【解决方案1】:

好吧,如果你确定编码的逻辑,那么你就可以实现它:

foreach (byte b in ba)
{
    if (b >= 32 && b <= 126)
    {
        hex.Append((char) b);
        continue;
    }

    ...

如果您正在寻找性能,您应该查看this answer,并可能对其中列出的方法之一进行一些调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-01
    • 2021-12-22
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2017-10-07
    • 2013-06-19
    相关资源
    最近更新 更多