怎么转换16进制Byte[]数组为字符串

anya 2011-03-30 03:04:24
如题。举例如何把 byte[] crc ={ 0x2e, 0x4a, 0xbd, 0x10 };

转换成string stra = "2e4abd10";

谢谢。在线等。
...全文
130 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
anya 2011-03-30
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 voodoo82 的回复:]
我晕,byte本来保存的就是一个数字啊。46和0x2e只是输出为string的格式是十进制还是十六进制。

运行下面的程序,结果就是你想要的。

C# code

static void Main(string[] args)
{
string stra = "2e4abd10";

byte[] ……
[/Quote]


嘿嘿,我真的不懂嘛。运行后OK。谢谢大家
  • 打赏
  • 举报
回复
 
byte[] inputBytes;
string inputString = System.Convert.ToBase64String(inputBytes);
voodoo82 2011-03-30
  • 打赏
  • 举报
回复
我晕,byte本来保存的就是一个数字啊。46和0x2e只是输出为string的格式是十进制还是十六进制。

运行下面的程序,结果就是你想要的。

static void Main(string[] args)
{
string stra = "2e4abd10";

byte[] result = ParseByteArray(stra);
PrintByteArray(result);
}

static byte[] ParseByteArray(string str)
{
int arrayLength = str.Length / 2;
byte[] byteArray = new byte[arrayLength];

for (int i = 0; i < arrayLength; ++i)
{
byteArray[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}

return byteArray;
}

static void PrintByteArray(byte[] byteArray)
{
Console.Write("{");

foreach (byte item in byteArray)
{
Console.Write(" 0x" + item.ToString("x02"));
}

Console.WriteLine(" }");
}

anya 2011-03-30
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ningweidong 的回复:]
string hexString = "2e";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
[/Quote]

好意思,我真的不懂,就是跟踪出来的结果是46,不是 byte[] crc ={ 0x2e}这种格式。
anya 2011-03-30
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 voodoo82 的回复:]
反过来只能自己写代码了。

C# code

static void Main(string[] args)
{
string stra = "2e4abd10";

byte[] result = ParseByteArray(stra);
}

static b……
[/Quote]


可是这样跟踪断点得到的结果是
result[0]、result[1]、result[2]、result[3]
分别是46、74、189、16

也不是我想实现的这种格式啊
转换成
byte[] crc ={ 0x2e, 0x4a, 0xbd, 0x10 };
ningweidong 2011-03-30
  • 打赏
  • 举报
回复
string hexString = "2e";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
voodoo82 2011-03-30
  • 打赏
  • 举报
回复
反过来只能自己写代码了。

static void Main(string[] args)
{
string stra = "2e4abd10";

byte[] result = ParseByteArray(stra);
}

static byte[] ParseByteArray(string str)
{
int arrayLength = str.Length / 2;
byte[] byteArray = new byte[arrayLength];

for (int i = 0; i < arrayLength; ++i)
{
byteArray[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}

return byteArray;
}

anya 2011-03-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ningweidong 的回复:]
ToString("x02")格式化成2位
[/Quote]

谢谢,我刚才就用这个代码调试成功了。

可以再问下吗?就是如果反过来把那个转成字节数组怎么转呢【因为程序中别的地方用到】。

比如把string stra = "2e4abd10";

转换成
byte[] crc ={ 0x2e, 0x4a, 0xbd, 0x10 };



ningweidong 2011-03-30
  • 打赏
  • 举报
回复
ToString("x02")格式化成2位
ningweidong 2011-03-30
  • 打赏
  • 举报
回复
string s;
for (i=0;i<4;i++)
{
s += byte[i].ToString("x");
}

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧