我的字符串包含字节(例如 0x27),基本上我需要做的是将包含字节数据的字符串数组转换为 byte
数据类型,然后我可以将其编码为 UTF8
,所以它显示有意义的信息。
1个字符串数组包含:
0x37, 0x32, 0x2d, 0x38, 0x33, 0x39, 0x37, 0x32,0x2d, 0x30, 0x31
我需要将其转换为字节数组,这可能吗?
我的代码是:
string strData;
string strRaw;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = Data;
XmlElement xmlDocElement = xmlDoc.DocumentElement;
strData = xmlDocElement.GetAttribute("datalabel").ToString();
strRaw = xmlDocElement.GetAttribute("rawdata").ToString();
string[] arrData = strData.Split(' ');
string[] arrRaw = strRaw.Split(' ');
感谢您的帮助。
最佳答案
可以用几种方式解释“字符串包含字节”。您可以通过多种方式将字符串提取为字节。基于UTF8编码将字符串直接转成字节:
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
其他编码当然也有类似的方法。
忽略以上内容
您的评论大大改变了问题的阅读方式!如果您的字符串只是十六进制(即字节未编码为字符串),只需将十六进制转换为整数即可。有点像....
var b = Convert.ToUInt32(str.Substring(2), 16)
// For an array
var bytes = new byte[arrData.Length];
for(var i = 0; i < arrData.Length; i++) {
bytes[i] = (byte)Convert.ToUInt32(arrData[i].Substring(2), 16);
}
关于C# 将字符串内容转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317509/