简体   繁体   English

C# 2.0 中的十六进制到字节 []

[英]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.假设有一个字符串hexString = "0x12""0x45"等。如何将字符串转换为另一个字节 [],如下所示。 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,当我尝试如下连接 substring 时,

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

I don't know how to fix it.我不知道如何解决它。 thanks.谢谢。 etc.等等

Have you tried searching for it first?您是否尝试过先搜索它?
Try this: How to convert hex to a byte array?试试这个: 如何将十六进制转换为字节数组?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM