开发者

Bit convector : Get byte array from string

When I have a string like "0xd8 0xff 0xe0" I do

Text.Split(' ')开发者_JS百科.Select(part => byte.Parse(part, System.Globalization.NumberStyles.HexNumber)).ToArray();

But if I got string like "0xd8ffe0" I don't know what to do ?

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. But using LINQ for this is probably not the best approach. 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.

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. 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[]:

    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.

  2. byte[] or any IEnumerable<Byte> -> Hex String:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜