I'm printing an "unsigned long" value to HEX via:

println(cardCode, HEX);

The value that I'm getting is: 69fb879d

I need it to be reversed as: 9d87fb69

I populate cardCode via the code:

for (i=1;i<bitCount;i++)
  cardCode <<=1;
  cardCode |= databits[i];

going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.

I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal? Is this even enough information to go on?

  • 1
    What exactly is in databits?
    – Majenko
    Jan 17 '16 at 23:52

Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the builtin functions provided by the compiler (AVR GCC).

unsigned long cardCode;
Serial.print(__builtin_bswap32(cardCode), HEX);

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.

uint16_t __builtin_bswap16(uint16_t);
uint32_t __builtin_bswap32(uint32_t);

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.

#define htonl(x) __builtin_bswap32((uint32_t) (x))



The title of this question is "Reverse the order of a hex string" but it was actually about reversing byte order in an unsigned long int.

Here is an answer for reverse the order of a string (null terminated vector of char).

There is a standard function for that in the C string function library.

char* strrev(char* s);


  • Sorry, misleading question title. It was about reversing the byte order of a value that became a hex string, and not reversing the string itself. Thanks
    – ZacWolf
    Jan 19 '16 at 15:24
  • 2
    No problem! I just wanted to add this alternative answer for googlers. It also strengthens the original answer somewhat. Jan 19 '16 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.