words.h (1979B)
1 // 2 // Word access and byte-swapping functions specific to x86-32 3 // 4 #ifndef X86_32_WORDS_H 5 #define X86_32_WORDS_H 6 7 #include <inttypes.h> 8 9 10 // Efficient byte-swap functions for x86-32 11 static inline uint16_t 12 bswap16(uint16_t v) { 13 asm("xchgb %%al,%%ah" : "=a" (v) : "a" (v)); 14 return v; 15 } 16 17 static inline uint32_t 18 bswap32(uint32_t v) { 19 asm("bswapl %%eax" : "=a" (v) : "a" (v)); 20 return v; 21 } 22 23 static inline uint64_t 24 bswap64(uint64_t v) { 25 return ((uint64_t)bswap32(v) << 32) | bswap32(v >> 32); 26 } 27 28 29 // Utility macros/functions for converting 30 // between host byte order and little-endian VX32 byte order. 31 // The x86 is little-endian already, so these are no-ops. 32 #define htol16(x) (x) 33 #define ltoh16(x) (x) 34 #define htol32(x) (x) 35 #define ltoh32(x) (x) 36 #define htol64(x) (x) 37 #define ltoh64(x) (x) 38 39 40 // Utility macros/functions for converting 41 // between host byte order and big-endian ("network") byte order. 42 #define htob16(x) bswap16(x) 43 #define btoh16(x) bswap16(x) 44 #define htob32(x) bswap32(x) 45 #define btoh32(x) bswap32(x) 46 #define htob64(x) bswap64(x) 47 #define btoh64(x) bswap64(x) 48 49 50 // Macros to access unaligned words in memory - trivial on the x86 51 #define getu16(p) (*(uint16_t*)(p)) // host byte order 52 #define getu32(p) (*(uint32_t*)(p)) 53 #define getu64(p) (*(uint64_t*)(p)) 54 #define getu16l(p) getu16(p) // little-endian 55 #define getu32l(p) getu32(p) 56 #define getu64l(p) getu64(p) 57 #define getu16n(p) bswap16(getu16(p)) // big-endian 58 #define getu32n(p) bswap32(getu32(p)) 59 #define getu64n(p) bswap64(getu64(p)) 60 61 #define putu16(p, v) (*(uint16_t*)(p) = (v)) // host byte order 62 #define putu32(p, v) (*(uint32_t*)(p) = (v)) 63 #define putu64(p, v) (*(uint64_t*)(p) = (v)) 64 #define putu16l(p, v) putu16((p), (v)) // little-endian 65 #define putu32l(p, v) putu32((p), (v)) 66 #define putu64l(p, v) putu64((p), (v)) 67 #define putu16n(p, v) putu16((p), bswap16(v)) // big-endian 68 #define putu32n(p, v) putu32((p), bswap32(v)) 69 #define putu64n(p, v) putu64((p), bswap64(v)) 70 71 72 #endif // X86_32_WORDS_H