Pregunta

Cuando tengo una cadena como "0xd8 0xff 0xE0" Tengo

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

Pero si llegué cadena como "0xd8ffe0" No sé qué hacer?

También soy capaz de recomendaciones de cómo escribir matriz de bytes como una cadena.

¿Fue útil?

Solución

necesidad de restregar la cadena antes de empezar a analizarlo. En primer lugar, retire el 0x, entonces simplemente omitir ningún espacio a medida que enumera la cadena. Pero el uso de LINQ para esto probablemente no es el mejor enfoque. Por un lado, el código no será muy fácil de leer y que va a ser difícil de pasar por si eres de depuración. Pero también, hay algunos trucos que puede hacer para hacer conversiones de hex / byte muy rápido. Por ejemplo, no utilice Byte.Parse, pero en su lugar usar una matriz de indexación para "mirar hacia arriba" el valor correspondiente.

Hace un tiempo he implementado una clase HexEncoding que se deriva de la clase de bases que codifica al igual que ASCIIEncoding y UTF8Encoding, etc. Su uso es muy sencillo. Está bastante bien optimizado también, lo cual puede ser muy importante en función del tamaño de los datos.

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

Aquí está la clase completa, sé que es un poco grande para un puesto, pero me he despojado ver los comentarios doc.

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

Otros consejos

  1. Hex String a 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);
    }
    

    Si usted tiene "0x" en el que comienza debe saltarse dos bytes.

  2. byte[] o cualquier IEnumerable<Byte> -> Hex String:

    return sequence.Aggregate(string.Empty,
                              (result, value) =>  result + 
                                                  string.Format(CultureInfo.InvariantCulture, "{0:x2}", value));
    
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top