Question

Quand j'ai une chaîne comme "0xD8 0xff 0xE0" Je fais

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

Mais si je suis chaîne comme « 0xd8ffe0 » Je ne sais pas quoi faire?

aussi que je suis en mesure de recommandations sur la façon d'écrire tableau d'octets comme une chaîne.

Était-ce utile?

La solution

Vous devez frotter votre chaîne avant de commencer à l'analyser. Tout d'abord, retirer le 0x, puis juste sauter tous les espaces que vous énumérez la chaîne. Mais en utilisant LINQ pour cela est probablement pas la meilleure approche. D'une part, le code ne sera pas très lisible et il sera difficile à parcourir si vous le débogage. Mais, il y a aussi quelques trucs que vous pouvez faire pour effectuer des conversions hex / octet très rapide. Par exemple, ne pas utiliser Byte.Parse, mais au lieu d'utiliser l'indexation de tableau pour « rechercher » la valeur correspondante.

A quelque temps que je mis en œuvre une classe HexEncoding qui dérive de la classe de base de codage tout comme ASCIIEncoding et UTF8Encoding, etc. Son utilisation est très simple. Il est assez bien optimisé trop qui peut être très important en fonction de la taille de vos données.

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

Voici la classe complète, je sais que c'est un peu grand pour un poste, mais je l'ai déshabillé les commentaires 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

Autres conseils

  1. Hex String à 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 vous avez "0x" au début de vous devriez sauter deux octets.

  2. byte[] ou tout IEnumerable<Byte> -> Hex String:

    return sequence.Aggregate(string.Empty,
                              (result, value) =>  result + 
                                                  string.Format(CultureInfo.InvariantCulture, "{0:x2}", value));
    
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top