【发布时间】:2014-01-22 09:43:17
【问题描述】:
下面是我正在尝试解决的代码(十六进制到十进制的转换).. 我发现错误出现在我在代码中注释的地方..
请提供解决方案以纠正..
static void Main(string[] args)
{
byte[] byteData;
int n;
byteData = GetBytesFromHexString("001C0014500C0A5B06A4FFFFFFFFFFFFFFFFFFFFFFFFFFFF");
n = byteData.Length;
Console.WriteLine(n);
string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n); //error
Console.WriteLine(s);
Console.ReadLine();
}
public static byte[] GetBytesFromHexString(string hexString)
{
//MessageBox.Show("getbytes ");
if (hexString == null)
return null;
if (hexString.Length % 2 == 1)
hexString = '0' + hexString; // Up to you whether to pad the first or last byte
byte[] data = new byte[hexString.Length / 2];
for (int i = 0; i < data.Length; i++)
{
data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
Console.WriteLine(data[i]);
}
我得到的输出是: “\0\0P\f\n[����������������” 转换后的十进制值未编码。
更新: 预期输出为“0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255”
【问题讨论】:
-
您希望
Console.WriteLine(s);的输出是什么? -
我得到了未编码的 System.Byte[] ..
-
代码完美运行:提供十六进制数字的字符串,将其转换为字节数组(data[0] = 0,data[1] = 0x1c = 28 等),转换字节数组到一个字符串(假设数组包含UTF8)一个显示它。因为十六进制字符串包含一些无法显示的字符(例如 0x1C、0x14 和 0xFF),所以输出看起来很奇怪,但并非不正确。所以,@MaxYakimets 的问题仍然存在:你期待什么?
-
@venerik 谢谢你的回复.. 从我得到的方法返回数据作为 System.Byte [] wen 它转换为字符串我得到那个输出.. 请帮助我