![](/img/trans.png)
[英]How to convert a byte array with hexadecimal contents to string with decimal in c#
[英]C# Convert String CONTENTS to byte array
我的字符串包含字节(例如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);
}
如果您在char中有每个字节,并且只想不使用编码就将其转换为字节数组,请使用;
string blip = "\x4A\x62";
byte[] blop = (from ch in blip select (byte)ch).ToArray();
如果要立即使用UTF8编码进行转换,请使用
string blip = "\x4A\x62";
var blop = System.Text.Encoding.UTF8.GetBytes(blip);
给定您的字符串是“ 0x37、0x32、0x2d,0x38、0x33、0x39、0x37、0x32、0x2d,0x30、0x31”或类似的字符串,您可以像这样获得字节值;
string input = "0x37, 0x32, 0x2d, 0x38, 0x33, 0x39, 0x37, 0x32, 0x2d, 0x30, 0x31";
string[] bytes = input.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
byte[] values = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
values[i] = byte.Parse(bytes[i].Substring(2,2), System.Globalization.NumberStyles.AllowHexSpecifier);
Console.WriteLine(string.Format("{0}", values[i]));
}
一旦拥有它们,就需要将它们输入适当的Encoder / Decoder中以获取字符串。
您应该能够执行以下操作:
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.