0

I have a device (hardware I cannot modify) that I have to communicate with data bytes. The problem I am experiencing is that I cannot simply send value converted to byte. As an example, I have value of 23, that has to be converted into the 4-byte command:

byte[0] -> MSB

byte[1] -> Mid Hi

byte[2] -> Mid Lo

byte[3] -> LSB

I cannot simply convert 25 -> 0x19 and use it like that. I am not a person who understands much of a lower-level language, I am truly trying to learn, but I know I have to shift bytes. My assumption is something like this:

int value = 23;

byte[0] = (value >> 24) & 0xFF;

byte[1] = (value >> 16) & 0xFF;

byte[2] = (value >> 8) & 0xFF;

byte[3] = value & 0xFF;

Is this correct? Will this produce outcome I am looking for? As an example how would you translate FF FF FF FB back to INT (based on the description above):

MSB: ff

Mid Hi: ff

Mid Lo:: ff

LSB: fb

What does this represent?

zuboje
  • 696
  • 3
  • 11
  • 28
  • 1
    Does this answer your question? [Converting an int into a 4 byte char array (C)](https://stackoverflow.com/questions/3784263/converting-an-int-into-a-4-byte-char-array-c) (long story short, yes, it's right) – Nick is tired Aug 26 '20 at 08:30
  • @Nick I've looked into that but I am not sure it solves my problem, because that logic will generate 0x00 0x00 0x00 0x19 and that is not the result that I am looking for. Or I am just not really understanding this? – zuboje Aug 26 '20 at 08:34
  • 1
    For your second part, translating back to `int`, you just do the [same thing in reverse](https://stackoverflow.com/questions/34943835/convert-four-bytes-to-integer-using-c/34944089) – Nick is tired Aug 26 '20 at 08:36

0 Answers0