0

Assume there is a string hexString = "0x12" or "0x45" etc. How can I convert the string to another byte[] as below. Thanks.

byte[] myByte = new byte[2];
myByte[0] = 0x1;
myByte[1] = 0x2;

or

myByte[0] = 0x4;
myByte[1] = 0x5;

When I try to concatenate the substring as below,

myByte[0] = '0x' + '4'; // Show compile error. It doesn't work.

I don't know how to fix it. thanks. etc.

Nano HE
  • 1,879
  • 7
  • 28
  • 39
  • 2
    So you want to store each hex digit in its own byte, instead of the more natural two hex digits per byte representation? – Yuliy May 31 '11 at 02:43

2 Answers2

1

Have you tried searching for it first?
Try this: How to convert hex to a byte array?

Community
  • 1
  • 1
bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • I thought, there is a little different on my question. I am not need convert the whole Hex string to byte[]. What I need is take out the individual number from the hex numberic string, and linked with '0x' before each of them as invidual hex number. – Nano HE May 31 '11 at 02:36
  • @Nano: What? If you just want to take a part of the string use `hexString.Substring()` [{msdn}](http://msdn.microsoft.com/en-us/library/system.string.substring.aspx). If you want to split the string into many, you can use `string.Split()`[{msdn}](http://msdn.microsoft.com/en-us/library/system.string.split.aspx) – bevacqua May 31 '11 at 02:40
  • I updated on my post. I want to concatenate the substring actually. – Nano HE May 31 '11 at 02:45
1

Are looking for something like this?

string hex = "0123456789abcdef";

string input = "0x45";
Debug.Assert(Regex.Match(input, "^0x[0-9a-f]{2}$").Success);

byte[] result = new byte[2];
result[0] = (byte)hex.IndexOf(input[2]);
result[1] = (byte)hex.IndexOf(input[3]);

// result[0] == 0x04
// result[1] == 0x05
dtb
  • 213,145
  • 36
  • 401
  • 431