I'm working on CAN Frames, in order to decode their payload, I have to reverse their order.
The payload is a uint8_t payload[8]
(8 bytes in the payload) read in the can frame with an external function that works properly.
I have this function :
static inline uint64_t reverse_byte_order(uint64_t x)
{
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
return x;
}
So basically i just call reverse_byte_order(*(uint64_t*)payload)
, but after some tests we couldn't get the right messages after decoding, and realized the problem came from this function.
One test that doesn't work is putting payload[0]=0x40
and everything else to 0x00. The output is 0, whereas it should be 0x 40 00 00 00 00 00 00 00.
Any helped would be appreciated.
Edit : Here is a MCVE you can copy paste into your IDE if you want to do some testing :
#include <stdint.h>
static inline uint64_t reverse_byte_order(uint64_t x)
{
printf("\nInitial x : %016x", x);
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
printf("\nFirst x : %016x", x); //in our example here it doesn't work anymore as x is 0
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
printf("\nSecond x : %016x", x);
x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
printf("\nFinal x : %016x", x);
return x;
}
int main(int argc, char const *argv[])
{
uint8_t data[8];
data[0]=0x11;
data[1]=0x00;
data[2]=0x00;
data[3]=0x00;
data[4]=0x00;
data[5]=0x00;
data[6]=0x00;
data[7]=0x00;
uint64_t indata = reverse_byte_order(*(uint64_t*)data);
}