C# byte[] 到十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/623104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
byte[] to hex string
提问by
How do I convert a byte[]
to a string
? Every time I attempt it, I get
如何将 a 转换byte[]
为 a string
?每次我尝试它时,我都会得到
System.Byte[]
System.Byte[]
instead of the value.
而不是价值。
Also, how do I get the value in Hex instead of a decimal?
另外,如何获取十六进制而不是十进制的值?
回答by Gregory Higley
You have to know the encoding of the string represented in bytes, but you can say System.Text.UTF8Encoding.GetString(bytes)
or System.Text.ASCIIEncoding.GetString(bytes)
. (I'm doing this from memory, so the API may not be exactly correct, but it's very close.)
您必须知道以字节表示的字符串的编码,但您可以说System.Text.UTF8Encoding.GetString(bytes)
或System.Text.ASCIIEncoding.GetString(bytes)
。(我是凭记忆做的,所以 API 可能不完全正确,但非常接近。)
For the answer to your second question, see this question.
有关第二个问题的答案,请参阅此问题。
回答by Quintin Robinson
Well I don't convert bytes to hex often so I have to say I don't know if there is a better way then this, but here is a way to do it.
好吧,我不经常将字节转换为十六进制,所以我不得不说我不知道是否有更好的方法,但这是一种方法。
StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
sb.Append(b.ToString("X2"));
string hexString = sb.ToString();
回答by Ash
As others have said it depends on the encoding of the values in the byte array. Despite this you need to be very careful with this sort of thing or you may try to convert bytes that are not handled by the chosen encoding.
正如其他人所说,这取决于字节数组中值的编码。尽管如此,您需要对此类事情非常小心,否则您可能会尝试转换所选编码未处理的字节。
Jon Skeet has a good articleabout encoding and unicode in .NET. Recommended reading.
回答by Michael Buen
Hex, Linq-fu:
十六进制,Linq-fu:
string.Concat(ba.Select(b => b.ToString("X2")).ToArray())
UPDATE with the times
与时俱进
As noted by @RubenBartelink, the code that don't have a conversion of IEnumerable<string>
to an array: ba.Select(b => b.ToString("X2"))
does not work prior to 4.0, the same code is now working on 4.0.
正如@RubenBartelink 所指出的,没有转换为IEnumerable<string>
数组的代码:ba.Select(b => b.ToString("X2"))
在 4.0 之前不起作用,相同的代码现在在 4.0 上工作。
This code...
这段代码...
byte[] ba = { 1, 2, 4, 8, 16, 32 };
string s = string.Concat(ba.Select(b => b.ToString("X2")));
string t = string.Concat(ba.Select(b => b.ToString("X2")).ToArray());
Console.WriteLine (s);
Console.WriteLine (t);
...prior to .NET 4.0, the output is:
...在 .NET 4.0 之前,输出为:
System.Linq.Enumerable+<CreateSelectIterator>c__Iterator10`2[System.Byte,System.String]
010204081020
On .NET 4.0 onwards, string.Concat has an overload that accepts IEnumerable. Hence on 4.0, the above code will have same output for both variables s and t
从 .NET 4.0 开始,string.Concat 有一个接受 IEnumerable 的重载。因此,在 4.0 上,上述代码对于变量 s 和 t 将具有相同的输出
010204081020
010204081020
Prior to 4.0, ba.Select(b => b.ToString("X2"))
goes to overload (object arg0)
, the way for the IEnumerable<string>
to go to a proper overload, i.e. (params string[] values)
, is we need to convert the IEnumerable<string>
to string array. Prior to 4.0, string.Concat has 10 overload functions, on 4.0 it is now 12
在 4.0 之前,ba.Select(b => b.ToString("X2"))
转到重载(object arg0)
,IEnumerable<string>
转到适当重载的方式,即(params string[] values)
我们需要将 转换IEnumerable<string>
为字符串数组。在 4.0 之前,string.Concat 有 10 个重载函数,在 4.0 上现在是 12 个
回答by Guffa
There is a built in method for this:
有一个内置的方法:
byte[] data = { 1, 2, 4, 8, 16, 32 };
string hex = BitConverter.ToString(data);
Result: 01-02-04-08-10-20
结果:01-02-04-08-10-20
If you want it without the dashes, just remove them:
如果你想要没有破折号,只需删除它们:
string hex = BitConverter.ToString(data).Replace("-", string.Empty);
Result: 010204081020
结果:010204081020
If you want a more compact representation, you can use Base64:
如果您想要更紧凑的表示,可以使用 Base64:
string base64 = Convert.ToBase64String(data);
Result: AQIECBAg
结果:AQIECBAg
回答by mloskot
You combine LINQ with string methods:
您将 LINQ 与字符串方法结合使用:
string hex = string.Join("",
bin.Select(
bin => bin.ToString("X2")
).ToArray());
回答by kgriffs
I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:
我喜欢使用扩展方法进行这样的转换,即使它们只是包装标准库方法。在十六进制转换的情况下,我使用以下手动调整(即快速)算法:
public static string ToHex(this byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
byte b;
for(int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx]=(char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
}
return new string(c);
}
public static byte[] HexToBytes(this string str)
{
if (str.Length == 0 || str.Length % 2 != 0)
return new byte[0];
byte[] buffer = new byte[str.Length / 2];
char c;
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
{
// Convert first half of byte
c = str[sx];
buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);
// Convert second half of byte
c = str[++sx];
buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
}
return buffer;
}
回答by Matthew Whited
Nice way to do this with LINQ...
用 LINQ 做到这一点的好方法......
var data = new byte[] { 1, 2, 4, 8, 16, 32 };
var hexString = data.Aggregate(new StringBuilder(),
(sb,v)=>sb.Append(v.ToString("X2"))
).ToString();
回答by Nathan Moinvaziri
Here is another method:
这是另一种方法:
public static string ByteArrayToHexString(byte[] Bytes)
{
StringBuilder Result = new StringBuilder(Bytes.Length * 2);
string HexAlphabet = "0123456789ABCDEF";
foreach (byte B in Bytes)
{
Result.Append(HexAlphabet[(int)(B >> 4)]);
Result.Append(HexAlphabet[(int)(B & 0xF)]);
}
return Result.ToString();
}
public static byte[] HexStringToByteArray(string Hex)
{
byte[] Bytes = new byte[Hex.Length / 2];
int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1)
{
Bytes[x] = (byte)(HexValue[Char.ToUpper(Hex[i + 0]) - '0'] << 4 |
HexValue[Char.ToUpper(Hex[i + 1]) - '0']);
}
return Bytes;
}
Alternatively, you could pre-build the translation table like so to achieve even faster results:
或者,您可以像这样预先构建翻译表以获得更快的结果:
回答by markn
Here is a extension method for byte array (byte[]), e.g.,
这是字节数组(byte[])的扩展方法,例如,
var b = new byte[] { 15, 22, 255, 84, 45, 65, 7, 28, 59, 10 };
Console.WriteLine(b.ToHexString());
public static class HexByteArrayExtensionMethods
{
private const int AllocateThreshold = 256;
private const string UpperHexChars = "0123456789ABCDEF";
private const string LowerhexChars = "0123456789abcdef";
private static string[] upperHexBytes;
private static string[] lowerHexBytes;
public static string ToHexString(this byte[] value)
{
return ToHexString(value, false);
}
public static string ToHexString(this byte[] value, bool upperCase)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length == 0)
{
return string.Empty;
}
if (upperCase)
{
if (upperHexBytes != null)
{
return ToHexStringFast(value, upperHexBytes);
}
if (value.Length > AllocateThreshold)
{
return ToHexStringFast(value, UpperHexBytes);
}
return ToHexStringSlow(value, UpperHexChars);
}
if (lowerHexBytes != null)
{
return ToHexStringFast(value, lowerHexBytes);
}
if (value.Length > AllocateThreshold)
{
return ToHexStringFast(value, LowerHexBytes);
}
return ToHexStringSlow(value, LowerhexChars);
}
private static string ToHexStringSlow(byte[] value, string hexChars)
{
var hex = new char[value.Length * 2];
int j = 0;
for (var i = 0; i < value.Length; i++)
{
var b = value[i];
hex[j++] = hexChars[b >> 4];
hex[j++] = hexChars[b & 15];
}
return new string(hex);
}
private static string ToHexStringFast(byte[] value, string[] hexBytes)
{
var hex = new char[value.Length * 2];
int j = 0;
for (var i = 0; i < value.Length; i++)
{
var s = hexBytes[value[i]];
hex[j++] = s[0];
hex[j++] = s[1];
}
return new string(hex);
}
private static string[] UpperHexBytes
{
get
{
return (upperHexBytes ?? (upperHexBytes = new[] {
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
"B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
"C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
"D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
"E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" }));
}
}
private static string[] LowerHexBytes
{
get
{
return (lowerHexBytes ?? (lowerHexBytes = new[] {
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
"b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
"c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
"d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
"e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff" }));
}
}
}