繁体   English   中英

位对流器:从字符串获取字节数组

[英]Bit convector : Get byte array from string

当我有一个类似“ 0xd8 0xff 0xe0”的字符串时,我会

Text.Split(' ').Select(part => byte.Parse(part, System.Globalization.NumberStyles.HexNumber)).ToArray();

但是,如果我得到类似“ 0xd8ffe0”的字符串,我不知道该怎么办?

我也可以建议如何将字节数组写为一个字符串。

开始解析之前,您需要先清理字符串。 首先,删除前导0x,然后在枚举字符串时跳过所有空格。 但是为此使用LINQ可能不是最佳方法。 一方面,该代码不太容易阅读,并且如果您要调试,则很难单步执行。 而且,您可以采取一些技巧来非常快速地进行十六进制/字节转换。 例如,不要使用Byte.Parse,而是使用数组索引来“查找”相应的值。

前一段时间,我实现了一个HexEncoding类,该类从Encoding基类派生而来,非常类似于ASCIIEncoding和UTF8Encoding等。使用它非常简单。 它也进行了很好的优化,这可能非常重要,具体取决于数据的大小。

var enc = new HexEncoding();
byte[] bytes = enc.GetBytes(str); // convert hex string to byte[]
str = enc.GetString(bytes);       // convert byte[] to hex string

这是完整的课程,我知道这对于发布来说有点大,但是我已经删除了文档注释。

public sealed class HexEncoding : Encoding
{

    public static readonly HexEncoding Hex = new HexEncoding( );

    private static readonly char[] HexAlphabet;
    private static readonly byte[] HexValues;

    static HexEncoding( )
    {

        HexAlphabet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        HexValues = new byte[255];
        for ( int i = 0 ; i < HexValues.Length ; i++ ) {
            char c = (char)i;
            if ( "0123456789abcdefABCDEF".IndexOf( c ) > -1 ) {
                HexValues[i] = System.Convert.ToByte( c.ToString( ), 16 );
            }   // if
        }   // for

    }

    public override string EncodingName
    {
        get
        {
            return "Hex";
        }
    }

    public override bool IsSingleByte
    {
        get
        {
            return true;
        }
    }

    public override int GetByteCount( char[] chars, int index, int count )
    {
        return count / 2;
    }

    public override int GetBytes( char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex )
    {

        int ci = charIndex;
        int bi = byteIndex;

        while ( ci < ( charIndex + charCount ) ) {

            char c1 = chars[ci++];
            char c2 = chars[ci++];

            byte b1 = HexValues[(int)c1];
            byte b2 = HexValues[(int)c2];

            bytes[bi++] = (byte)( b1 << 4 | b2 );

        }   // while

        return charCount / 2;

    }

    public override int GetCharCount( byte[] bytes, int index, int count )
    {
        return count * 2;
    }

    public override int GetChars( byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex )
    {

        int ci = charIndex;
        int bi = byteIndex;

        while ( bi < ( byteIndex + byteCount ) ) {

            int b1 = bytes[bi] >> 4;
            int b2 = bytes[bi++] & 0xF;

            char c1 = HexAlphabet[b1];
            char c2 = HexAlphabet[b2];

            chars[ci++] = c1;
            chars[ci++] = c2;

        }   // while

        return byteCount * 2;

    }

    public override int GetMaxByteCount( int charCount )
    {
        return charCount / 2;
    }

    public override int GetMaxCharCount( int byteCount )
    {
        return byteCount * 2;
    }

}   // class
  1. 十六进制Stringbyte[]

     byte[] bytes = new byte[value.Length / 2]; for (int i = 0; i < value.Length; i += 2) { bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16); } 

    如果"0x""0x" ,则应跳过两个字节。

  2. byte[]或任何IEnumerable<Byte> ->十六进制String

     return sequence.Aggregate(string.Empty, (result, value) => result + string.Format(CultureInfo.InvariantCulture, "{0:x2}", value)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM