Page 1 of 1

How to swap bytes in MCU

Posted: 10-Jan-2023, 23:05
by Administrator

Code: Select all

/// Network to host byte order conversion.
#if defined (__CC_ARM)
  // ARM Compiler 4/5
  #define ntohl(v)              (uint32_t)(__rev(v))
  #define ntohs(v)              (uint16_t)(__rev(v) >> 16)
#else
  // ARM Compiler 6
  #define ntohl(v)              __builtin_bswap32((uint32_t)(v))
  #define ntohs(v)              __builtin_bswap16((uint16_t)(v))
#endif

Code: Select all

/// Host to network byte order conversion.
#ifndef htons
	#define htons(v)                ntohs(v)
	#define htonl(v)                ntohl(v)
#endif
static inline SWAPB(uint16_t w) { return ntohs(w); }