Long little endian conversion

I am doing some work with a nextion display i have had laying around for a number of years.
Just getting to know the thing a little and found that if it send number values it sends in a little enian fasion over 4 byte. I have writen a small routine that uses a 4 byte array, a long, bitwise or and bit shifting.

Although it works fine in testing it feels a little clunky in code so i was wondering is there a more effective way? The final project is most likely going to be on something like a teensy 4 or arduino mega for the ease of muliple serial ports.

        input[0] = nextion.read();;
        input[1] = nextion.read();;
        input[2] = nextion.read();;
        input[3] = nextion.read();;

        b = input[3] << 8;
        b = b | input[2] << 8;
        b = b | input[1] << 8;
        b = b | input[0];
uint32_t b = 0;
for (int i = 0; i < 4; i++)
  b = (b << 8) + nextion.read();

There's a built in function for that - Other Builtins (Using the GNU Compiler Collection (GCC)).

// https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

void setup() {

  Serial.begin(115200);
  uint32_t bigVar = 0x12345678;
  Serial.print("\n");
  Serial.print(bigVar,HEX);
  Serial.print("\n");
  Serial.print(__builtin_bswap32(bigVar), HEX);
  Serial.print("\n");
}

void loop() {
  // put your main code here, to run repeatedly:
}

YMMV

1 Like

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