web-dev-qa-db-fra.com

octet [] en chaîne hexagonale

Comment convertir un byte[] en un string? Chaque fois que je tente, je reçois

System.Byte []

au lieu de la valeur.

Aussi, comment puis-je obtenir la valeur en hexadécimal au lieu d'un nombre décimal?

307
user34537

Il existe une méthode intégrée pour cela:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

Résultat: 01-02-04-08-10-20

Si vous le voulez sans les tirets, supprimez-les simplement:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

Résultat: 010204081020

Si vous voulez une représentation plus compacte, vous pouvez utiliser Base64:

string base64 = Convert.ToBase64String(data);

Résultat: AQIECBAg

555
Guffa

Je pensais essayer de comparer la vitesse de chacune des méthodes énumérées ici. J'ai basé le code de test de vitesse sur cela.

Le résultat est que BitConverter + String.Replace semble être plus rapide que la plupart des autres méthodes simples. Mais la vitesse peut être améliorée avec des algorithmes tels que ByteArrayToHexString de Nathan Moinvaziri ou ToHex de Kurt.

J'ai aussi trouvé intéressant que string.Concat et string.Join soient beaucoup plus lents que les implémentations de StringBuilder pour les chaînes longues, mais similaires pour les tableaux plus courts. Probablement en raison du développement de StringBuilder sur les chaînes plus longues, la définition de la taille initiale devrait donc annuler cette différence.

  • A pris chaque morceau de code d'une réponse ici:
  • BitConvertRep = Réponse de Guffa, BitConverter et String.Replace (Je le recommande dans la plupart des cas)
  • StringBuilder = Réponse de Quintin Robinson, pour chaque caractère StringBuilder.Append
  • LinqConcat = Réponse de Michael Buen, string.Concat de Linq construit un tableau
  • LinqJoin = Réponse de mloskot, string.Join of Linq built array
  • LinqAgg = Réponse de Matthew Whited, IEnumerable.Aggregate avec StringBuilder
  • ToHex = Answer by Kurt, définit les caractères d'un tableau, en utilisant des valeurs d'octet pour obtenir un hex
  • ByteArrayToHexString = Réponse de Nathan Moinvaziri, environ la même vitesse que le ToHex ci-dessus, et est probablement plus facile à lire (je le recommanderais pour la vitesse)
  • ToHexFromTable = lié par la réponse de Nathan Moinvaziri, pour moi, il est proche de la même vitesse que le précédent 2 mais nécessite un tableau de 256 chaînes pour toujours exister

Avec: LONG_STRING_LENGTH = 1000 * 1024;

  • Calcul du BitConvertRep Temps écoulé 27 202 ms (le plus rapide intégré/simple)
  • Calcul du StringBuilder Temps écoulé 75 723 ms (StringBuilder sans réallocation)
  • Calcul LinqConcat Temps écoulé 182,094 ms
  • Calcul LinqJoin Temps écoulé 181,142 ms
  • Temps de calcul LinqAgg écoulé 93 087 ms (StringBuilder avec réallocation)
  • Temps de calcul ToHex Temps écoulé 19 167 ms (le plus rapide)

Avec: LONG_STRING_LENGTH = 100 * 1024;, Résultats similaires

  • Calcul de BitConvertReplace Temps écoulé 3431 ms
  • Calcul du StringBuilder Temps écoulé 8289 ms
  • Calcul LinqConcat Temps écoulé 21512 ms
  • Calcul LinqJoin Temps écoulé 19433 ms
  • Calcul LinqAgg Temps écoulé 9230 ms
  • ToHex temps de calcul écoulé 1976 ms

Avec: int MANY_STRING_COUNT = 1000;int MANY_STRING_LENGTH = 1024; (Même nombre d'octets que le premier test, mais dans des tableaux différents)

  • Calcul de BitConvertReplace Temps écoulé 25,680 ms
  • Calcul du StringBuilder Temps écoulé 78,411 ms
  • Calcul LinqConcat Temps écoulé 101,233 ms
  • Calcul de LinqJoin Temps écoulé 99 311 ms
  • Calcul LinqAgg Temps écoulé 84,660 ms
  • ToHex temps de calcul écoulé 18,221 ms

Avec: int MANY_STRING_COUNT = 2000;int MANY_STRING_LENGTH = 20;

  • Calcul de BitConvertReplace Temps écoulé 1347 ms
  • Calcul du StringBuilder Temps écoulé 3234 ms
  • Calcul LinqConcat Temps écoulé 5013 ms
  • Calcul LinqJoin Temps écoulé 4826 ms
  • Calcul LinqAgg Temps écoulé 3589 ms
  • ToHex temps de calcul écoulé 772 ms

Code de test que j'ai utilisé:

void Main()
{
    int LONG_STRING_LENGTH = 100 * 1024;
    int MANY_STRING_COUNT = 1024;
    int MANY_STRING_LENGTH = 100;

    var source = GetRandomBytes(LONG_STRING_LENGTH);

    List<byte[]> manyString = new List<byte[]>(MANY_STRING_COUNT);
    for (int i = 0; i < MANY_STRING_COUNT; ++i)
    {
        manyString.Add(GetRandomBytes(MANY_STRING_LENGTH));
    }

    var algorithms = new Dictionary<string,Func<byte[], string>>();
    algorithms["BitConvertReplace"] = BitConv;
    algorithms["StringBuilder"] = StringBuilderTest;
    algorithms["LinqConcat"] = LinqConcat;
    algorithms["LinqJoin"] = LinqJoin;
    algorithms["LinqAgg"] = LinqAgg;
    algorithms["ToHex"] = ToHex;
    algorithms["ByteArrayToHexString"] = ByteArrayToHexString;

    Console.WriteLine(" === Long string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            pair.Value(source);
        });
    }

    Console.WriteLine(" === Many string test");
    foreach (var pair in algorithms) {
        TimeAction(pair.Key + " calculation", 500, () =>
        {
            foreach (var str in manyString)
            {
                pair.Value(str);
            }
        });
    }
}

// Define other methods and classes here
static void TimeAction(string description, int iterations, Action func) {
    var watch = new Stopwatch();
    watch.Start();
    for (int i = 0; i < iterations; i++) {
        func();
    }
    watch.Stop();
    Console.Write(description);
    Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}

//static byte[] GetRandomBytes(int count) {
//  var bytes = new byte[count];
//  (new Random()).NextBytes(bytes);
//  return bytes;
//}
static Random Rand = new Random();
static byte[] GetRandomBytes(int count) {
    var bytes = new byte[count];
    Rand.NextBytes(bytes);
    return bytes;
}


static string BitConv(byte[] data)
{
    return BitConverter.ToString(data).Replace("-", string.Empty);
}
static string StringBuilderTest(byte[] data)
{
    StringBuilder sb = new StringBuilder(data.Length*2);
    foreach (byte b in data)
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}
static string LinqConcat(byte[] data)
{
    return string.Concat(data.Select(b => b.ToString("X2")).ToArray());
}
static string LinqJoin(byte[] data)
{
    return string.Join("",
        data.Select(
            bin => bin.ToString("X2")
            ).ToArray());
}
static string LinqAgg(byte[] data)
{
    return data.Aggregate(new StringBuilder(),
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();
}
static string ToHex(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx] = (char)(b > 9 ? b - 10 + 'A' : b + '0');
    }

    return new string(c);
}
public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length*2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
        {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
        }

    return Result.ToString();
}

Autre réponse avec un processus similaire , je n'ai pas encore comparé nos résultats.

85
Thymine

Hex, Linq-fu:

string.Concat(ba.Select(b => b.ToString("X2")).ToArray())

PDATE avec les temps

Comme noté par @RubenBartelink, le code qui n'a pas de conversion de IEnumerable<string> en un tableau: ba.Select(b => b.ToString("X2")) ne fonctionne pas avant la version 4.0, le même code fonctionne maintenant sur la version 4.0.

Ce code ...

byte[] ba = { 1, 2, 4, 8, 16, 32 };

string s = string.Concat(ba.Select(b => b.ToString("X2")));
string t = string.Concat(ba.Select(b => b.ToString("X2")).ToArray());

Console.WriteLine (s);
Console.WriteLine (t);

... avant .NET 4.0, le résultat est:

System.Linq.Enumerable+<CreateSelectIterator>c__Iterator10`2[System.Byte,System.String]
010204081020

A partir de .NET 4.0, string.Concat a une surcharge qui accepte IEnumerable. Donc sur 4.0, le code ci-dessus aura le même résultat pour les deux variables s et t

010204081020
010204081020

Avant la version 4.0, ba.Select(b => b.ToString("X2")) surcharge (object arg0), ce qui permet au IEnumerable<string> d’obtenir une surcharge appropriée, c’est-à-dire (params string[] values), si nous devons convertir le IEnumerable<string> en string array. Avant la version 4.0, string.Concat avait 10 fonctions de surcharge, la version 4.0 en a maintenant 12.

69
Michael Buen

Voici une autre méthode:

public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length * 2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
    {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
    }

    return Result.ToString();
}

public static byte[] HexStringToByteArray(string Hex)
{
    byte[] Bytes = new byte[Hex.Length / 2];
    int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 
       0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
       0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

    for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1)
    {
        Bytes[x] = (byte)(HexValue[Char.ToUpper(Hex[i + 0]) - '0'] << 4 |
                          HexValue[Char.ToUpper(Hex[i + 1]) - '0']);
    }

    return Bytes;
}

Vous pouvez également pré-construire la table de traduction de manière à obtenir des résultats encore plus rapides:

http://blogs.msdn.com/b/blambert/archive/2009/02/22/blambert-codesnip-fast-byte-array-to-hex-string-conversion.aspx

28

Bien, je ne convertis pas souvent les octets en sortilège, donc je dois dire que je ne sais pas s'il existe un meilleur moyen, mais voici une façon de le faire.

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
    sb.Append(b.ToString("X2"));

string hexString = sb.ToString();
20
Quintin Robinson

J'aime utiliser des méthodes d'extension comme celle-ci pour les conversions, même si elles enveloppent simplement les méthodes de bibliothèque standard. Dans le cas de conversions hexadécimales, j'utilise les algorithmes suivants rapides accordés manuellement:

public static string ToHex(this byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];

    byte b;

    for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx) 
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);

        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }

    return new string(c);
}

public static byte[] HexToBytes(this string str)
{
    if (str.Length == 0 || str.Length % 2 != 0)
        return new byte[0];

    byte[] buffer = new byte[str.Length / 2];
    char c;
    for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
    {
        // Convert first half of byte
        c = str[sx];
        buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);

        // Convert second half of byte
        c = str[++sx];
        buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
    }

    return buffer;
}
20
kgriffs

Je pensais que je devrais fournir une réponse. De mon test cette méthode est la plus rapide

public static class Helper
{
    public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
    public static string ToHex(this IEnumerable<byte> array)
    {
        StringBuilder s = new StringBuilder();
        foreach (var v in array)
            s.Append(HexTbl[v]);
        return s.ToString();
    }
    public static string ToHex(this byte[] array)
    {
        StringBuilder s = new StringBuilder(array.Length*2);
        foreach (var v in array)
            s.Append(HexTbl[v]);
        return s.ToString();
    }
}
11
user34537

Méthodes d'extension très rapides (avec inversion):

public static class ExtensionMethods {
    public static string ToHex(this byte[] data) {
        return ToHex(data, "");
    }
    public static string ToHex(this byte[] data, string prefix) {
        char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int i = 0, p = prefix.Length, l = data.Length;
        char[] c = new char[l * 2 + p];
        byte d;
        for(; i < p; ++i) c[i] = prefix[i];
        i = -1;
        --l;
        --p;
        while(i < l) {
            d = data[++i];
            c[++p] = lookup[d >> 4];
            c[++p] = lookup[d & 0xF];
        }
        return new string(c, 0, c.Length);
    }
    public static byte[] FromHex(this string str) {
        return FromHex(str, 0, 0, 0);
    }
    public static byte[] FromHex(this string str, int offset, int step) {
        return FromHex(str, offset, step, 0);
    }
    public static byte[] FromHex(this string str, int offset, int step, int tail) {
        byte[] b = new byte[(str.Length - offset - tail + step) / (2 + step)];
        byte c1, c2;
        int l = str.Length - tail;
        int s = step + 1;
        for(int y = 0, x = offset; x < l; ++y, x += s) {
            c1 = (byte)str[x];
            if(c1 > 0x60) c1 -= 0x57;
            else if(c1 > 0x40) c1 -= 0x37;
            else c1 -= 0x30;
            c2 = (byte)str[++x];
            if(c2 > 0x60) c2 -= 0x57;
            else if(c2 > 0x40) c2 -= 0x37;
            else c2 -= 0x30;
            b[y] = (byte)((c1 << 4) + c2);
        }
        return b;
    }
}

Bat tous les autres dans le test de vitesse ci-dessus:

=== Test de longue chaîne
BitConvertReplace le calcul Temps écoulé 2415 ms
Calcul de StringBuilder Temps écoulé 5668 ms
Calcul LinqConcat Temps écoulé 11826 ms
Calcul LinqJoin Temps écoulé 9323 ms
Temps de calcul LinqAgg écoulé 7444 ms
Temps de calcul ToHexTable Temps écoulé 1028 ms
Calcul de ToHexAcidzombie Temps écoulé 1035 ms
Calcul ToHexPatrick temps écoulé 814 ms
Calcul du ToHexKurt Temps écoulé 1604 ms
ByteArrayToHexString calcule le temps écoulé 1330 ms

=== Plusieurs test de chaîne
Calcul de BitConvertReplace Temps écoulé 2238 ms
Calcul du StringBuilder Temps écoulé 5393 ms
Calcul LinqConcat Temps écoulé 9043 ms
Calcul LinqJoin Temps écoulé 9131 ms
Temps de calcul LinqAgg écoulé 7324 ms
Temps de calcul ToHexTable Temps écoulé 968 ms
Calcul de ToHexAcidzombie Temps écoulé 969 ms
Calcul ToHexPatrick temps écoulé 956 ms
Calcul du ToHexKurt Temps écoulé 1547 ms
ByteArrayToHexString calcule le temps écoulé 1277 ms

9
Patrick

Juste pour ajouter une réponse à la pile, il y a une classe System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary que j'ai utilisée et qui peut convertir des octets en hexa:

string hex = new SoapHexBinary(bytes).ToString();
byte[] bytes = SoapHexBinary.Parse(hex).Value;

Vous ne savez pas exactement comment il se compare (benchmark) à d'autres implémentations, mais IMO est assez simple, en particulier pour la conversion d'octets à partir d'hex.

7
Allan

Avec:

byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x0D, 0x0E, 0x0F };
string hex = string.Empty;
data.ToList().ForEach(b => hex += b.ToString("x2"));
// use "X2" for uppercase hex letters
Console.WriteLine(hex);

Résultat: 0102030d0e0f

4
Barn Monkey

Vous devez connaître l'encodage de la chaîne représentée en octets, mais vous pouvez dire System.Text.UTF8Encoding.GetString(bytes) ou System.Text.ASCIIEncoding.GetString(bytes). (Je le fais de mémoire, alors l'API peut ne pas être exactement correcte, mais elle est très proche.)

Pour la réponse à votre deuxième question, voir cette question .

2
Gregory Higley

Personne ici n’a mentionné la raison pour laquelle vous obtenez la chaîne "System.Byte []" au lieu de la valeur, donc je le ferai.

Lorsqu'un objet est implicitement converti en String, le programme utilise par défaut la méthode public String ToString() de l'objet, héritée de System.Object:

public virtual string ToString()
{
    return this.GetType().ToString();
}

Si vous constatez que vous effectuez souvent cette conversion, vous pouvez simplement créer une classe wrapper et remplacer cette méthode de la manière suivante:

public override string ToString()
{
    // do the processing here
    // return the nicely formatted string
}

Maintenant, chaque fois que vous imprimez cet objet wrapper, vous obtiendrez votre valeur au lieu de celle de this.GetType().ToString().

2
Ozzy

Vous combinez LINQ avec des méthodes de chaîne:

string hex = string.Join("",
  bin.Select(
    bin => bin.ToString("X2")
      ).ToArray());
2
mloskot

Je ne sais pas si vous avez besoin de performance pour faire cela, mais voici la méthode la plus rapide pour convertir octet [] en chaîne hexagonale à laquelle je peux penser:

static readonly char[] hexchar = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static string HexStr(byte[] data, int offset, int len, bool space = false)
{
    int i = 0, k = 2;
    if (space) k++;
    var c = new char[len * k];
    while (i < len)
    {
        byte d = data[offset + i];
        c[i * k] = hexchar[d / 0x10];
        c[i * k + 1] = hexchar[d % 0x10];
        if (space && i < len - 1) c[i * k + 2] = ' ';
        i++;
    }
    return new string(c, 0, c.Length);
}
1
Toanzzz

Comme d'autres l'ont dit, cela dépend du codage des valeurs dans le tableau d'octets. Malgré cela, vous devez être très prudent avec ce genre de chose ou vous pouvez essayer de convertir des octets qui ne sont pas gérés par le codage choisi.

Jon Skeet a un bon article à propos de l'encodage et de l'unicode dans .NET. Lecture recommandée.

1
Ash

Je pense que j'ai fait un tableau d'octets au convertisseur de chaîne plus rapide:

public static class HexTable
{
    private static readonly string[] table = BitConverter.ToString(Enumerable.Range(0, 256).Select(x => (byte)x).ToArray()).Split('-');

    public static string ToHexTable(byte[] value)
    {
        StringBuilder sb = new StringBuilder(2 * value.Length);

        for (int i = 0; i < value.Length; i++)
            sb.Append(table[value[i]]);

        return sb.ToString();
    }

Et le test mis en place:

static void Main(string[] args)
{
        const int TEST_COUNT = 10000;
        const int BUFFER_LENGTH = 100000;

        Random random = new Random();

        Stopwatch sw = new Stopwatch();
        Stopwatch sw2 = new Stopwatch();

        byte[] buffer = new byte[BUFFER_LENGTH];
        random.NextBytes(buffer);

        sw.Start();
        for (int j = 0; j < TEST_COUNT; j++)
            HexTable.ToHexTable(buffer);

        sw.Stop();

        sw2.Start();
        for (int j = 0; j < TEST_COUNT; j++)
            ToHexChar.ToHex(buffer);

        sw2.Stop();

        Console.WriteLine("Hex Table Elapsed Milliseconds: {0}", sw.ElapsedMilliseconds);
        Console.WriteLine("ToHex Elapsed Milliseconds: {0}", sw2.ElapsedMilliseconds);
    }

La méthode ToHexChar.ToHEx () est la méthode ToHex () présentée précédemment.

Les résultats sont les suivants:

HexTable = 11808 ms ToHEx = 12168ms

Cela peut sembler peu différent, mais c'est encore plus rapide :)

1
Kris

Voici une méthode d'extension pour tableau d'octets (byte []), par exemple:

var b = new byte[] { 15, 22, 255, 84, 45, 65, 7, 28, 59, 10 };
Console.WriteLine(b.ToHexString());


public static class HexByteArrayExtensionMethods
{
    private const int AllocateThreshold = 256;
    private const string UpperHexChars = "0123456789ABCDEF";
    private const string LowerhexChars = "0123456789abcdef";
    private static string[] upperHexBytes;
    private static string[] lowerHexBytes;

    public static string ToHexString(this byte[] value)
    {
        return ToHexString(value, false);
    }

    public static string ToHexString(this byte[] value, bool upperCase)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        if (value.Length == 0)
        {
            return string.Empty;
        }

        if (upperCase)
        {
            if (upperHexBytes != null)
            {
                return ToHexStringFast(value, upperHexBytes);
            }

            if (value.Length > AllocateThreshold)
            {
                return ToHexStringFast(value, UpperHexBytes);
            }

            return ToHexStringSlow(value, UpperHexChars);
        }

        if (lowerHexBytes != null)
        {
            return ToHexStringFast(value, lowerHexBytes);
        }

        if (value.Length > AllocateThreshold)
        {
            return ToHexStringFast(value, LowerHexBytes);
        }

        return ToHexStringSlow(value, LowerhexChars);
    }

    private static string ToHexStringSlow(byte[] value, string hexChars)
    {
        var hex = new char[value.Length * 2];
        int j = 0;

        for (var i = 0; i < value.Length; i++)
        {
            var b = value[i];
            hex[j++] = hexChars[b >> 4];
            hex[j++] = hexChars[b & 15];
        }

        return new string(hex);
    }

    private static string ToHexStringFast(byte[] value, string[] hexBytes)
    {
        var hex = new char[value.Length * 2];
        int j = 0;

        for (var i = 0; i < value.Length; i++)
        {
            var s = hexBytes[value[i]];
            hex[j++] = s[0];
            hex[j++] = s[1];
        }

        return new string(hex);
    }

    private static string[] UpperHexBytes
    {
        get
        {
            return (upperHexBytes ?? (upperHexBytes = new[] {
                "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
                "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
                "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
                "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
                "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
                "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
                "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
                "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
                "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
                "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
                "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
                "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
                "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
                "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" }));
        }
    }

    private static string[] LowerHexBytes
    {
        get
        {
            return (lowerHexBytes ?? (lowerHexBytes = new[] {
                "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
                "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
                "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
                "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
                "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
                "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
                "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
                "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
                "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
                "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
                "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
                "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
                "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
                "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff" }));
        }
    }
}
1
markn

Belle façon de faire cela avec LINQ ...

var data = new byte[] { 1, 2, 4, 8, 16, 32 }; 
var hexString = data.Aggregate(new StringBuilder(), 
                               (sb,v)=>sb.Append(v.ToString("X2"))
                              ).ToString();
0
Matthew Whited
private static string GuidToRaw(Guid guid)
{
    byte[] bytes = guid.ToByteArray();

    int сharCount = bytes.Length * 2;
    char[] chars = new char[сharCount];

    int index = 0;
    for (int i = 0; i < сharCount; i += 2)
    {
        byte b = bytes[index++];
        chars[i] = GetHexValue((int)(b / 16));
        chars[i + 1] = GetHexValue((int)(b % 16));
    }
    return new string(chars, 0, chars.Length);
}

private static char GetHexValue(int i)
{
    return (char)(i < 10 ? i + 48 : i + 55);
}
0
alex1kirch