简体   繁体   English

C#字节转换

[英]C# Byte conversions

I get very confused when it comes up to byte conversation. 当谈到字节对话时,我感到非常困惑。

I need to do two convertions: 我需要进行两次转换:

1.We have a byte[] array { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35 }; 1.我们有一个byte []数组{0x30,0x31,0x32,0x33,0x34,0x35};

How do I convert it to string so I get "30 31 32 33 34 35". 如何将其转换为字符串,以便得到“ 30 31 32 33 34 35”。

2.We have the same byte[] array 2.我们有相同的byte []数组

Now I need to convert it to ASCII(0x30 = 0, 0x31 = 1, 0x32 = 2 and so on) 现在我需要将其转换为ASCII(0x30 = 0,0x31 = 1,0x32 = 2依此类推)

When done I should get "012345". 完成后,我应该得到“ 012345”。

How do I make both conversions? 如何进行两次转换?

var bytearr = new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35 };
var str = bytearr.Select(x => x.ToString("x2"));
var ascii = bytearr.Select(x => (char)x);

If you want the output as a single string (as opposed to IEnumerable s), you could do: 如果要将输出作为单个string (而不是IEnumerable ),则可以执行以下操作:

var str = String.Join(" ", bytearr.Select(x => x.ToString("x2")).ToArray());
var ascii = new string(bytearr.Select(x => (char)x).ToArray());
  1. This will format the numbers as hexadecimal with spaces between: 这会将数字格式化为十六进制,并在以下之间留有空格:

    string r1 = String.Join(" ", array.Select(n => n.ToString("x2")).ToArray()); 字符串r1 = String.Join(“”,array.Select(n => n.ToString(“ x2”))。ToArray());

  2. This will convert the bytes to ASCII: 这会将字节转换为ASCII:

    string r2 = Encoding.ASCII.GetString(array); 字符串r2 = Encoding.ASCII.GetString(array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM