How do I convert separate int values to hex byte array

徘徊边缘 提交于 2019-12-12 14:58:01

问题


I need to do some (new to me) int/hex/byte work and I am struggling to get it right. The tcp server on the other side is expecting Little Endian.

I need to send a byte array consisting of HEX values.

6000 needs to be sent as:

0x70, 0x17

19 needs to be sent as:

0x13, 0x00, 0x00, 0x00

The resulting byte array should look like this.

**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

I can get the hex value of 6000 as 1770 by using: .ToString("x4") I can get the hex value of 19 as 00000013 by using: .ToString("x8")

I have two questions:

  1. This (to my knowledge) is Big Endian. Short from chopping the string and manually rewriting it to reverse it, is there a .net routine that can do this for me?

  2. Once I have it reversed, how do I get

7017

in a byte array of:

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

Thanks in advance.


回答1:


You can use the BitConverter class to achieve the conversion. The result is actually already in the convention that you need. No Reversion is necessary

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"))));

Output:

6000 -> : 70170000
19 -> : 13000000

Here is a little method that does the job, with the amount of bytes that you desire:

public byte[] TransformBytes(int num, int byteLength)
{
    byte[] res = new byte[byteLength];

    byte[] temp = BitConverter.GetBytes(num);

    Array.Copy(temp, res, byteLength);

    return res;
}

Then you could call it and combine the result in a list like this:

List<byte> allBytesList = new List<byte>();

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"))));

Output:

All -> : 70 17 13 00 00 00 40 42 0F 00 A0 86 01 00 04

The List<byte> can be easily converted in the end to an array:

byte [] b_array = allBytesList.ToArray();


来源:https://stackoverflow.com/questions/45213196/how-do-i-convert-separate-int-values-to-hex-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!