Hex to byte[] in C# 2.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.
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
Have you tried searching for it first?
Try this: How to convert hex to a byte array?
精彩评论