如何在C#中将array[1]
转换为十六进制
array[1] = 1443484
我尝试了以下操作,但是无法编译:
StringBuilder hex = new StringBuilder(array[1].Length * 2);
foreach (byte b in array[1])
hex.AppendFormat("{0:x2}", b);
string value = hex.ToString();
答案 0 :(得分:1)
如果只想获取十六进制表示形式,则可以一次完成:
// 16069c
string value = Convert.ToString(array[1], 16);
或
string value = array[1].ToString("x");
或(填充版本:至少8
个字符)
// 0016069c
string value = array[1].ToString("x8");
如果您想使用byte
进行操作,请尝试BitConverter
类
byte[] bytes = BitConverter.GetBytes(array[1]);
string value = string.Concat(bytes.Select(b => b.ToString("x2")));
您修改的代码:
using System.Runtime.InteropServices; // For Marshal
...
// Marshal.SizeOf - length in bytes (we don't have int.Length in C#)
StringBuilder hex = new StringBuilder(Marshal.SizeOf(array[1]) * 2);
// BitConverter.GetBytes - byte[] representation
foreach (byte b in BitConverter.GetBytes(array[1]))
hex.AppendFormat("{0:x2}", b);
// You can well get "9c061600" (reversed bytes) instead of "0016069c"
// if BitConverter.IsLittleEndian == true
string value = hex.ToString();