Convert int to byte array little-endian

I’m working on my code for the Argon (Device OS: 2.3.0). I have an array of 3 bytes and I want to convert the value of a counter in little-endian format for the last two bytes of the array.

I wrote the code below which is working, is there a better way to do this?


uint8_t writebuf[3] = {0xA1, 0x00, 0x00};  //last two bytes -> number to be increased by 1 little-endian format at each iteration

for (int j = 0; j <= 600; j++)
   // take the value of last two bytes of writebuff and add value of "j"
   // i=1   -> 0x01, 0x00
   // i=2   -> 0x02, 0x00
   // i=511 -> 0xFF, 0x01

   int a = j%256;
   int b = (j-j%256)/256;
   writebuf[1] = (byte)a;
   writebuf[2] = (byte)b;"Raw Value  %02x %02x %02x", writebuf[0], writebuf[1], writebuf[2]);


Raw Value a1 00 00
Raw Value a1 01 00
Raw Value a1 02 00
Raw Value a1 58 02

I’m not quite sure if I understand what you are trying to get to.
Big and little endian only refer to the order of the bytes of a multi byte value.
So if you have big endian int16_t stored in a two byte array you would just need to swap the two bytes round in order to store them little endian.

No divisions or modulo operations required.

(for illustration purposes)

union I2A {
  int16_t i;             // overlay 2-byte-integer
  uint8_t a[sizeof(i)];  // with byte-array of same size 
} i2a;
uint8_t writebuf[3] = { 0xA1, 0x00, 0x00 };

writebuf[2] = i2a.a[0];
writebuf[1] = i2a.a[1];"Raw Value  %02x %02x %02x", writebuf[0], writebuf[1], writebuf[2]);

Without the union you could do this

  int16_t i;
  uint8_t writebuf[3] = { 0xA1, 0x00, 0x00 };

  writebuf[1] = i & 0xFF; // only keep the bottom byte
  writebuf[2] = i >> 8;   // shift the top byte down 8 bits (bottom byte will be purged in the process)"Raw Value  %02x %02x %02x", writebuf[0], writebuf[1], writebuf[2]);

BTW, multiplications, divisions and modulo operations by powers of 2 will typically be caught be the optimizer and translated to shift and mask operations. So the processing cost of your original code wouldn’t be that far off.
However, since I like to advocate for understanding what’s going on behind the scenes I like to show how to do it without relying on any black-box to repair what I could have done right from the start :wink:


I choose the second option proposed.
Since I could not make it work in another way I basically figure it out a mathematical way to do it. Thanks for the tip and the working code, really appreciate.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.