Skip to main content
2 of 6
added 330 characters in body
hazymat
  • 121
  • 4

How to swap byte order (ethernet client.write)

I'm reading a 24-bit ADC value into a uint32. Using SPI bus, here's the logic:

value = SPI.transfer(0);   // read first 8 bits (MSB first)
value <<= 8;               // shift bits left
value |= SPI.transfer(0);  // read next 8 bits
value <<= 8;               // shift bits left
value |= SPI.transfer(0);  // read final 8 bits

As such I'm left with this ADC reading:

00000000 11111111 11111111 11111111
         MSB                    LSB

(Ignore the leading zeros for now.)

Now I transfer this value over ethernet like so:

client.write((const byte*) &value, sizeof(value));

The problem is this:

  • The value is stored as MS bit first.
  • client.write() transmits it LS byte first.

So at the other end, I receive the data like this:

11111111 11111111 11111111 00000000
     LSB          MSB

I understand this is the expected behaviour, but obviously I would like to switch the BYTE order around, so that it resembles the original value.

What is the best way to achieve this? Perhaps I should do some bit shifting at the point of reading the ADC, to accommodate the fact that client.write() sends the least significant byte first, like this:

  byte1 = SPI.transfer(0);
  byte2 = SPI.transfer(0);
  byte3 = SPI.transfer(0);
  response = byte3;
  response <<= 8;
  response = byte2;
  response <<= 8;
  response = byte1;

Is this the most efficient way in terms of clock cycles?

Please note that my MCU is a Teensy 4.1, and I'm transferring 10,000 readings per second. I would like to keep the clock cycles for any necessary bitwise operations to a minimum, so that the timing of ADC readings are affected as little as possible.

hazymat
  • 121
  • 4