如何将单独的int值转换为hex字节数组

我需要做一些(对我而言)int / hex / byte工作,我正在努力做到正确。 另一方面的tcp服务器期待Little Endian。

我需要发送一个由HEX值组成的字节数组。

需要发送6000作为:

0x70, 0x17

需要发送19作为:

0x13, 0x00, 0x00, 0x00

参数

生成的字节数组应如下所示。

 **FROM THE MANUFACTURER** Complete message should be: 0x70, 0x17, 0x13, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00, 0xA0, 0x86, 0x01, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04 

我可以通过使用: .ToString("x4")得到6000的hex值为1770我可以使用: .ToString("x8")将hex值19作为00000013

我有两个问题:

  1. 这(据我所知)是Big Endian。 切断字符串并手动重写以反转字符串,是否有一个.net例程可以为我做这个?

  2. 一旦我扭转了,我该怎么做

7017

在一个字节数组中:

[0] = 0x70, [1] = 0x17

提前致谢。

您可以使用BitConverter类来实现转换。 结果实际上已经在您需要的约定中。 不需要回归

 byte[] res6000 = BitConverter.GetBytes(6000); byte[] res19 = BitConverter.GetBytes(19); // TEST OUTPUT for example Console.WriteLine(" 6000 -> : " + String.Join("", res6000.Select(x => x.ToString("X2")))); Console.WriteLine(" 19 -> : " + String.Join("", res19.Select(x=>x.ToString("X2")))); 

输出:

6000 – >:70170000
19 – >:13000000

这是一个完成工作的小方法,具有您想要的字节数:

 public byte[] TransformBytes(int num, int byteLength) { byte[] res = new byte[byteLength]; byte[] temp = BitConverter.GetBytes(num); Array.Copy(temp, res, byteLength); return res; } 

然后你可以调用它并将结果组合在一个列表中,如下所示:

 List allBytesList = new List(); allBytesList.AddRange(TransformBytes( 6000, 2)); allBytesList.AddRange(TransformBytes( 19, 4)); allBytesList.AddRange(TransformBytes(1000000, 4)); allBytesList.AddRange(TransformBytes( 100000, 4)); allBytesList.AddRange(TransformBytes( 4, 1)); Console.WriteLine(" All -> : " + String.Join(" ", allBytesList.Select(x => x.ToString("X2")))); 

输出:

全部 – >:70 17 13 00 00 00 40 42 0F 00 A0 86 01 00 04

List可以很容易地转换为数组:

 byte [] b_array = allBytesList.ToArray();