Cross-platform definition of _byteswap_uint64 and _byteswap_ulong
Asked Answered
N

2

7

Visual Studio defines _byteswap_uint64 and _byteswap_ulong in stdlib.h.

Am I right to assume, that this is not standard and won't compile on Linux or Darwin?

Is there a way to define these includes in a cross-platform way?

Nittygritty answered 20/1, 2017 at 19:19 Comment(0)
P
17

Google's CityHash source code uses this code:

https://github.com/google/cityhash/blob/8af9b8c2b889d80c22d6bc26ba0df1afb79a30db/src/city.cc#L50

#ifdef _MSC_VER

#include <stdlib.h>
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)

#elif defined(__APPLE__)

// Mac OS X / Darwin features
#include <libkern/OSByteOrder.h>
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)

#elif defined(__sun) || defined(sun)

#include <sys/byteorder.h>
#define bswap_32(x) BSWAP_32(x)
#define bswap_64(x) BSWAP_64(x)

#elif defined(__FreeBSD__)

#include <sys/endian.h>
#define bswap_32(x) bswap32(x)
#define bswap_64(x) bswap64(x)

#elif defined(__OpenBSD__)

#include <sys/types.h>
#define bswap_32(x) swap32(x)
#define bswap_64(x) swap64(x)

#elif defined(__NetBSD__)

#include <sys/types.h>
#include <machine/bswap.h>
#if defined(__BSWAP_RENAME) && !defined(__bswap_32)
#define bswap_32(x) bswap32(x)
#define bswap_64(x) bswap64(x)
#endif

#else

#include <byteswap.h>

#endif
Postdiluvian answered 10/9, 2017 at 5:41 Comment(0)
S
1

I'm not aware of a cross-platform and efficient way of doing that. If you use GCC you can use the builtin byteswap like: uint32_t __builtin_bswap32 (uint32_t x)

Those are fast but certainly not portable... unless you wrap the various versions under the appropriate ifdefs

Cheers Francesco

Strangeness answered 25/5, 2017 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.