Guest User

Guest User

  • Tech Writer
  • 357
  • 121.1k

Hex to Bytes

Mar 11 2012 2:11 PM
Hi

Please see my comments next to each coded expression and correct where necessary.

// Declare a static method which returns an array of bytes and accepts 1 input argument named hex of type string.
private static byte[] HexToBytes(string hex)

// Construct a new instance\object of type byte and pass the hex value and length property divided by two. Store the result in a local variable named bytes.
byte[] bytes = new byte[hex.Length / 2];

// Initialize i to 0, assign the hex Length property to be less than i / 2 and then iterate the loop with i++
for (int i = 0; i < hex.Length / 2; i++)

// Use the Substring method of string passing in the values i times 2 and 2 and then store the return value in a local variable named code.
string code = hex.Substring(i * 2, 2);

// Pass the code reference and the enum NumberStyles.HexNumber to the byte Parse method and then Set this to the reference bytes in position 0. 
bytes[i] = byte.Parse(code, NumberStyles.HexNumber);

// Return the bytes reference.
return bytes;

Thanks

Answers (14)