Domanda

Quando ho una stringa come "0xd8 0xff 0xE0" Faccio

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

Ma se ho ottenuto stringa come "0xd8ffe0" Io non so cosa fare?

anche io sono in grado di raccomandazioni su come scrivere array di byte come una stringa.

È stato utile?

Soluzione

È necessario macchia la stringa prima di iniziare l'analisi di esso. In primo luogo, rimuovere il prefisso 0x, poi basta saltare tutti gli spazi come si enumera la stringa. Ma usando LINQ per questo non è probabilmente l'approccio migliore. Per uno, il codice non sarà molto leggibile e sarà difficile per scorrere se siete il debug. Ma anche, ci sono alcuni trucchi che si possono fare per rendere conversioni esadecimale / byte molto veloce. Ad esempio, non utilizzare Byte.Parse, ma invece utilizzare matrice indicizzazione per "cercare" il valore corrispondente.

Qualche tempo fa ho implementato una classe HexEncoding che deriva dalla classe base Encoding molto simile ASCIIEncoding e UTF8Encoding, ecc Utilizzando è molto semplice. E 'abbastanza ben ottimizzato troppo che può essere molto importante a seconda della dimensione dei dati.

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

Ecco la classe completa, lo so che è un pò grande per un post, ma ho spogliato i commenti 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

Altri suggerimenti

  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);
    }
    

    Se avete "0x" All'inizio si dovrebbe saltare due byte.

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

    return sequence.Aggregate(string.Empty,
                              (result, value) =>  result + 
                                                  string.Format(CultureInfo.InvariantCulture, "{0:x2}", value));
    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top