简体   繁体   中英

How do I convert separate int values to hex byte array

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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