10

Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

For testing my encryption algorithm I have being provided keys, plain text and their resulting cipher text.

The keys and plaintext are in strings

How do i convert it to a hex byte array??

Something like this : E8E9EAEBEDEEEFF0F2F3F4F5F7F8F9FA

To something like this :

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

Thanx in advance :)

Community
  • 1
  • 1
Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128
  • 1
    duplicate of http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array – jdehaan Jun 04 '10 at 07:20
  • duplicate of http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c too. Tho there are different solutions shown there, so maybe all topics can live :) – 0x49D1 Jun 04 '10 at 07:23

3 Answers3

16

Do you need this?

static class HexStringConverter
{
    public static byte[] ToByteArray(String HexString)
    {
        int NumberChars = HexString.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;
    }
}

Hope it helps.

Community
  • 1
  • 1
0x49D1
  • 8,505
  • 11
  • 76
  • 127
1

Sample code from MSDN:

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String 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.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue);
}

You only have to change it to split the string on every 2 chars instead of on spaces.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
0

did u mean this

StringBuilder Result = new StringBuilder();
    string HexAlphabet = "0123456789ABCDEF";

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

    return Result.ToString();
Johnny
  • 1,555
  • 3
  • 14
  • 23