简体   繁体   English

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

[英]Bit convector : Get byte array from string

When I have a string like "0xd8 0xff 0xe0" I do 当我有一个类似“ 0xd8 0xff 0xe0”的字符串时,我会

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

But if I got string like "0xd8ffe0" I don't know what to do ? 但是,如果我得到类似“ 0xd8ffe0”的字符串,我不知道该怎么办?

also I'm able for recommendations how to write byte array as one string. 我也可以建议如何将字节数组写为一个字符串。

You need to scrub your string before you start parsing it. 开始解析之前,您需要先清理字符串。 First, remove the leading 0x, then just skip any spaces as you enumerate the string. 首先,删除前导0x,然后在枚举字符串时跳过所有空格。 But using LINQ for this is probably not the best approach. 但是为此使用LINQ可能不是最佳方法。 For one, the code won't be very readable and it'll be hard to step through if you're debugging. 一方面,该代码不太容易阅读,并且如果您要调试,则很难单步执行。 But also, there are some tricks you can do to make hex/byte conversions very fast. 而且,您可以采取一些技巧来非常快速地进行十六进制/字节转换。 For example, don't use Byte.Parse, but instead use array indexing to "look up" the corresponding value. 例如,不要使用Byte.Parse,而是使用数组索引来“查找”相应的值。

A while back I implemented a HexEncoding class that derives from the Encoding base class much like ASCIIEncoding and UTF8Encoding, etc. Using it is very simple. 前一段时间,我实现了一个HexEncoding类,该类从Encoding基类派生而来,非常类似于ASCIIEncoding和UTF8Encoding等。使用它非常简单。 It's pretty well optimized too which can be very important depending on the size of your data. 它也进行了很好的优化,这可能非常重要,具体取决于数据的大小。

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

Here's the complete class, I know it's kinda big for a post but I've stripped out the doc comments. 这是完整的课程,我知道这对于发布来说有点大,但是我已经删除了文档注释。

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. Hex String to byte[] : 十六进制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); } 

    If you have "0x" at the beginning you should skip two bytes. 如果"0x""0x" ,则应跳过两个字节。

  2. byte[] or any IEnumerable<Byte> -> Hex String : 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