FreeRTOS_ntohl() for more than 32 bits

Hello!

I am working on a project where we receive 48 bytes (384 bits) from the network (using FreeRTOS_recvfrom). After receiving, we need to reverse the byte order. I only seem to find uint32_t FreeRTOS_ntohl( uint32_t ulValueToSwap ); which only allows reversing 32 bits at a time. What is the best way to reverse the byte order of this large amount of data?

Something like this?

#include <stdint.h>

void FreeRTOS_ntohl_array_32(uint32_t *array, size_t length) {
    for (size_t i = 0; i < length; i++) {
        array[i] = FreeRTOS_ntohl(array[i]);
    }
}

// Usage
uint32_t data[12]; // Your 384-bit data broken down into 32-bit chunks
FreeRTOS_ntohl_array_32(data, 12);

Or is there a better, more efficient, way?

Thanks!

Your implementation looks good to me!

Great, thanks a lot!

Are you saying that you need to reverse the order of all 48 bytes, or that you need to reverse the byte order of 12 4-byte words a word at a time?

If you’re using GCC, you might look at __builtin_bswap32 (and 16, 64, and 128, but not 48).

If you’re running on ARM there is a REV machine instruction that reverses the byte order in a data word. I believe x86 also has some kind of BSWAP instruction.

If you’re using GCC on ARM and you’re lucky, the bswap will compile to REV.

(This might already be realized by whatever FreeRTOS port you’re using.)

Yes, I need to reverse the order of all 48 bytes. I can provide some more context. I am writing an NTP client, so the NTP packet I get back is 48 bytes. I found this C code on GitHub which does roughly what I do ntpclient/source/c/main.c at master · lettier/ntpclient · GitHub (although my solution is based on the skeleton code from RFC 5905). I’ve based the project of this FreeRTOS/FreeRTOS-Plus/Demo/FreeRTOS_Plus_TCP_Echo_Qemu_mps2 at main · FreeRTOS/FreeRTOS · GitHub (but with UDP).

I guess it’s using GCC (specifically arm-none-eabi-gcc)?

See also NTPDemo.c, function prvSwapFields(). It calls FreeRTOS_htonl(), which works both on a little endian as well as on a big endian platform.
Note that FreeRTOS_htonl() depends on the macro ipconfigBYTE_ORDER.

NTPDemo.c is a simple implementation of an NTP client. The contents of an NTP packet is big endian.

See also ntpClient.h for the declarations of an NTP packet.

You will find a few GCC / Makefile testing projects here.