Search code examples
c#hextype-conversionbyteint64

How to convert from Int64 to hex and from hex to byte in c#


I am trying to send a byte array to micro controller over serial port. This is an example array which can successfully communicate with micro controller:

byte[] getCommandArray = new byte[7] { 0x02, 0x0D, 0x01, 0x03, 0x30, 0x44, 0x03 };

What I need to do is read different values from database, store them in a byte array send this array to the serial port. I read values from database as Int64. Also for a successful communication I need to convert these values to hex. For example if I read 13 from the database I need to write this to my array as 0x0D. I can convert 13 to 0x0D as hex string but I can't convert this to byte. If you have any other suggestions than this logic I would be appreciated.


Solution

  • If you simply want to get all of the bytes from your Int64 value, you can do that like this:

    Int64 myValueFromDB = 13;
    var asBytes = BitConverter.GetBytes(myValueFromDB);
    

    To check if this produces what you expect, you can print this result like this:

    Console.WriteLine("{{{0}}}", string.Join(",", asBytes.Select(x => "0x" + x.ToString("X2"))));    
    

    For your example, using the value of 13 for myValueFromDB, the output is:

    {0x0D,0x00,0x00,0x00,0x00,0x00,0x00,0x00}
    

    As you can see, the value of asBytes[0] is 0x0D, the other 7 bytes are 0.

    You can check this for yourself in this Fiddle;