Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to a Hex Byte Array? [duplicate]

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 :)

like image 725
Ranhiru Jude Cooray Avatar asked Jun 04 '10 07:06

Ranhiru Jude Cooray


People also ask

How can I convert a hex string to a byte array?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

How do you convert bytes to hexadecimal?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .

What is ByteArray?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.


1 Answers

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.

like image 189
0x49D1 Avatar answered Oct 10 '22 16:10

0x49D1