Comment convertir une chaîne en un tableau d’octets Hex?

Dupliquer possible:
Comment convertir un tableau d’octets en chaîne hexadécimale, et inversement, en C #?

Pour tester mon algorithme de chiffrement, on me fournit des clés, du texte brut et le texte chiffré obtenu.

Les clés et le texte en clair sont dans des chaînes

Comment puis-je le convertir en un tableau d’octets hexadécimal?

Quelque chose comme ça: E8E9EAEBEDEEEFF0F2F3F4F5F7F8F9FA

Pour quelque chose comme ça:

 byte[] key = new byte[16] { 0xE8, 0xE9, 0xEA, 0xEB, 0xED, 0xEE, 0xEF, 0xF0, 0xF2, 0xF3, 0xF4, 0xF5, 0xF7, 0xF8, 0xF9, 0xFA} ; 

Merci d’avance 🙂

Avez-vous besoin de cela ?

 static class HexSsortingngConverter { public static byte[] ToByteArray(Ssortingng HexSsortingng) { int NumberChars = HexSsortingng.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) { bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16); } return bytes; } } 

J'espère que ça aide.

Exemple de code à partir de MSDN :

 ssortingng hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21"; ssortingng[] hexValuesSplit = hexValues.Split(' '); foreach (Ssortingng hex in hexValuesSplit) { // Convert the number expressed in base-16 to an integer. int value = Convert.ToInt32(hex, 16); // Get the character corresponding to the integral value. ssortingng ssortingngValue = Char.ConvertFromUtf32(value); char charValue = (char)value; Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, ssortingngValue, charValue); } 

Il suffit de le changer pour scinder la chaîne tous les 2 caractères au lieu d’espaces.

avez-vous dire cela

 SsortingngBuilder Result = new SsortingngBuilder(); ssortingng HexAlphabet = "0123456789ABCDEF"; foreach (byte B in Bytes) { Result.Append(HexAlphabet[(int)(B >> 4)]); Result.Append(HexAlphabet[(int)(B & 0xF)]); } return Result.ToSsortingng();