Big endian conversion in Arduino

Hi All,

I'm retrieving some numbers from a modbus connection and need to convert them to big endian for the proper values. What will be optimum way of doing this on an Arduino Uno. I tried htonl in below code but it doesn't compile saying there is no function called "htonl"

#include <Ethernet.h>


void setup() {
  Serial.begin(115200);
}

void loop() {
  unsigned long host_number = 0x12345678; // Example decimal number
  unsigned long big_endian_number = htonl(host_number);

  Serial.print("Host number (decimal): ");
  Serial.println(host_number, HEX);

  Serial.print("Big-endian number (hex): ");
  Serial.println(big_endian_number, HEX);

  delay(2000);
}

How did you come up with that function name? What is it supposed to do?

Did you just copy some code from the web?

unsigned long host_number = 0x12345678; // Example decimal number

The comment above is incorrect. The "0x" indicates hexadecimal representation.

It is a standard C function to convert from host to network order. Network order is big endian.

Try:

#include <arpa/inet.h>

or;

#include <netinet/in.h>

See also: htonl(3) - Linux man page

Must admit, not tried it on an Arduino.

Yup this was copied from the google AI generated seqrch snippet. I have seen in many places mentioning this fuction available in network.h or someother standard network library. However it seems not in Arduino. Any other suggestions for this?

Nope. Not working.

Indeed. Just tried myself. They come up automatically in the editor, but do not actually compile, which results in 'No such file or directory'. Sorry about that.

It is no problem to swap bytes in a 32 bit integer, but why not tell us what you are really trying to do?

1 Like

This is htonl

#ifndef htonl
#define htonl(x) ( ((x)<<24 & 0xFF000000UL) | \
                   ((x)<< 8 & 0x00FF0000UL) | \
                   ((x)>> 8 & 0x0000FF00UL) | \
                   ((x)>>24 & 0x000000FFUL) )
#endif

Found it in w5100.h which I have installed. You can simply put this in your code, no additional libraries required.

See Ethernet/src/utility/w5100.h at master Ā· arduino-libraries/Ethernet Ā· GitHub

2 Likes
uint32_t __builtin_bswap32 (uint32_t x)

Thanks. This did work.