-1

I have the following string:

string hi = "0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b"

And I split it on the ',' character into an array:

string[] string1 = decrypted.Split(',');

Now I need a way to store string1 into a byte array so it looks like:

byte[] byte1 = {0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Agent Magma
  • 41
  • 1
  • 7
  • So you've taken a string (`hi`) and converted it into a string array (`string1`), but now you want to convert each element of the string array to a byte? What have you tried? – Joe Sewell Jul 21 '18 at 00:33
  • https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array You can take a reference from this above asked question. – Aditya Saurabh Jul 21 '18 at 00:40
  • It depends on the encoding and if it is little/bit endian. You can use : string myString = Encoding.UTF8.GetString(byte1); byte[] byte2 = Encoding.UTF8.GetBytes(myString); – jdweng Jul 21 '18 at 01:06

2 Answers2

4

You can convert a single string from hex to binary using Convert.ToByte(string, int) by passing 16 as the second parameter.

With this knowledge, and a little trimming and substringing, we can convert to an array of bytes with a little LINQ:

var byteArray = input
    .Split(',')
    .Select
    ( 
        s => Convert.ToByte
        (
            s.Trim().Substring(2),
            16
        ) 
    )
    .ToArray();

Example on DotNetFiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80
0
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                 .ToArray();

}

follow the same you will get your answer

  • This would only work with a stream of continuous digits. OP's string contains other things too. – John Wu Jul 21 '18 at 00:43