1

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.

vontarro
  • 339
  • 1
  • 3
  • 14
  • Have you seen http://stackoverflow.com/q/321370/1218281? – Cyral May 02 '15 at 18:35
  • Check if this helps: http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa – Sami May 02 '15 at 18:35
  • I have checked these links but I need to store my value as one byte not as byte array. Like I said I need to convert 13 to 0x0D and store 0x0D in my byte array. – vontarro May 02 '15 at 18:48
  • @vontarro, why does you example show a byte array containing 7 bytes, instead of the 8 you would get from an `Int64`? – Alex May 02 '15 at 19:56
  • @Alex all of them are different values. I am not sure is it possible but I need to store number 13 as 0x0D in my byte array. So just the second number of the array should represent the 13 as 0x0D – vontarro May 02 '15 at 23:33
  • @vontarro, have you looked if the code I provided in my answer works for you, i.e. gives the expected output? If it does not, please indicate what is different from what you expect. – Alex May 02 '15 at 23:35
  • @Alex it gives {0x37, 0x37, 0x37, 0x37, 0x37, 0x37, 0x37, 0x37} when the myValueFromDB is 13. However the expected output is a single 0x0D as byte. – vontarro May 02 '15 at 23:49
  • @vontarro, then I don't think you copied everything correctly. See this ["filddle"](https://dotnetfiddle.net/C8aNX2) with the code in my answer. It produces `{0x0D,0x00,0x00,0x00,0x00,0x00,0x00,0x00}` as the output, with the first by in `asBytes`, i.e `asBytes[0]` having the value 0x0D. – Alex May 03 '15 at 00:10

1 Answers1

3

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;

Alex
  • 13,024
  • 33
  • 62