138451Smsmith/* 238451Smsmith * Written by Manuel Bouyer <bouyer@netbsd.org>. 338451Smsmith * Public domain. 438451Smsmith */ 538451Smsmith 684221Sdillon#include <sys/cdefs.h> 784221Sdillon__FBSDID("$FreeBSD$"); 884221Sdillon 938451Smsmith#if defined(LIBC_SCCS) && !defined(lint) 1038451Smsmithstatic char *rcsid = "$NetBSD: bswap32.c,v 1.1 1997/10/09 15:42:33 bouyer Exp $"; 11222908Srodrigcstatic char *rcsid = "$NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger Exp $"; 1238451Smsmith#endif 1338451Smsmith 1438451Smsmith#include <sys/types.h> 1538451Smsmith 1638451Smsmith#undef bswap32 1738451Smsmith#undef bswap64 1838451Smsmith 19221358Srodrigcu_int32_t bswap32(u_int32_t x); 20221358Srodrigcu_int64_t bswap64(u_int64_t x); 21221358Srodrigc 2238451Smsmithu_int32_t 23221358Srodrigcbswap32(u_int32_t x) 2438451Smsmith{ 2538451Smsmith return ((x << 24) & 0xff000000 ) | 2638451Smsmith ((x << 8) & 0x00ff0000 ) | 2738451Smsmith ((x >> 8) & 0x0000ff00 ) | 2838451Smsmith ((x >> 24) & 0x000000ff ); 2938451Smsmith} 3038451Smsmith 3138451Smsmithu_int64_t 32221358Srodrigcbswap64(u_int64_t x) 33222908Srodrigc{ 34235939Sobrien#ifdef __LP64__ 35222908Srodrigc /* 36222908Srodrigc * Assume we have wide enough registers to do it without touching 37222908Srodrigc * memory. 38222908Srodrigc */ 39222908Srodrigc return ( (x << 56) & 0xff00000000000000UL ) | 40222908Srodrigc ( (x << 40) & 0x00ff000000000000UL ) | 41222908Srodrigc ( (x << 24) & 0x0000ff0000000000UL ) | 42222908Srodrigc ( (x << 8) & 0x000000ff00000000UL ) | 43222908Srodrigc ( (x >> 8) & 0x00000000ff000000UL ) | 44222908Srodrigc ( (x >> 24) & 0x0000000000ff0000UL ) | 45222908Srodrigc ( (x >> 40) & 0x000000000000ff00UL ) | 46222908Srodrigc ( (x >> 56) & 0x00000000000000ffUL ); 47222908Srodrigc#else 48222908Srodrigc /* 49222908Srodrigc * Split the operation in two 32bit steps. 50222908Srodrigc */ 51222908Srodrigc u_int32_t tl, th; 5238451Smsmith 53222908Srodrigc th = bswap32((u_int32_t)(x & 0x00000000ffffffffULL)); 54222908Srodrigc tl = bswap32((u_int32_t)((x >> 32) & 0x00000000ffffffffULL)); 55222908Srodrigc return ((u_int64_t)th << 32) | tl; 56222908Srodrigc#endif 57222908Srodrigc} 58