1/*
2 * Written by Manuel Bouyer <bouyer@netbsd.org>.
3 * Public domain.
4 */
5
6#include <sys/cdefs.h>
7__FBSDID("$FreeBSD$");
8
9#if defined(LIBC_SCCS) && !defined(lint)
10static char *rcsid = "$NetBSD: bswap32.c,v 1.1 1997/10/09 15:42:33 bouyer Exp $";
11static char *rcsid = "$NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger Exp $";
12#endif
13
14#include <sys/types.h>
15
16#undef bswap32
17#undef bswap64
18
19u_int32_t bswap32(u_int32_t x);
20u_int64_t bswap64(u_int64_t x);
21
22u_int32_t
23bswap32(u_int32_t x)
24{
25	return  ((x << 24) & 0xff000000 ) |
26			((x <<  8) & 0x00ff0000 ) |
27			((x >>  8) & 0x0000ff00 ) |
28			((x >> 24) & 0x000000ff );
29}
30
31u_int64_t
32bswap64(u_int64_t x)
33{
34#ifdef __LP64__
35	/*
36	 * Assume we have wide enough registers to do it without touching
37	 * memory.
38	 */
39	return  ( (x << 56) & 0xff00000000000000UL ) |
40		( (x << 40) & 0x00ff000000000000UL ) |
41		( (x << 24) & 0x0000ff0000000000UL ) |
42		( (x <<  8) & 0x000000ff00000000UL ) |
43		( (x >>  8) & 0x00000000ff000000UL ) |
44		( (x >> 24) & 0x0000000000ff0000UL ) |
45		( (x >> 40) & 0x000000000000ff00UL ) |
46		( (x >> 56) & 0x00000000000000ffUL );
47#else
48	/*
49	 * Split the operation in two 32bit steps.
50	 */
51	u_int32_t tl, th;
52
53	th = bswap32((u_int32_t)(x & 0x00000000ffffffffULL));
54	tl = bswap32((u_int32_t)((x >> 32) & 0x00000000ffffffffULL));
55	return ((u_int64_t)th << 32) | tl;
56#endif
57}
58