bswap.c revision 222908
1112158Sdas/*
2112158Sdas * Written by Manuel Bouyer <bouyer@netbsd.org>.
3112158Sdas * Public domain.
4112158Sdas */
5112158Sdas
6112158Sdas#include <sys/cdefs.h>
7112158Sdas__FBSDID("$FreeBSD: head/lib/libstand/bswap.c 222908 2011-06-10 01:13:15Z rodrigc $");
8112158Sdas
9112158Sdas#if defined(LIBC_SCCS) && !defined(lint)
10112158Sdasstatic char *rcsid = "$NetBSD: bswap32.c,v 1.1 1997/10/09 15:42:33 bouyer Exp $";
11112158Sdasstatic char *rcsid = "$NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger Exp $";
12112158Sdas#endif
13112158Sdas
14112158Sdas#include <sys/types.h>
15112158Sdas
16112158Sdas#undef bswap32
17112158Sdas#undef bswap64
18112158Sdas
19112158Sdasu_int32_t bswap32(u_int32_t x);
20112158Sdasu_int64_t bswap64(u_int64_t x);
21112158Sdas
22112158Sdasu_int32_t
23112158Sdasbswap32(u_int32_t x)
24112158Sdas{
25112158Sdas	return  ((x << 24) & 0xff000000 ) |
26112158Sdas			((x <<  8) & 0x00ff0000 ) |
27112158Sdas			((x >>  8) & 0x0000ff00 ) |
28112158Sdas			((x >> 24) & 0x000000ff );
29165743Sdas}
30165743Sdas
31112158Sdasu_int64_t
32112158Sdasbswap64(u_int64_t x)
33112158Sdas{
34112158Sdas#ifdef _LP64
35112158Sdas	/*
36112158Sdas	 * Assume we have wide enough registers to do it without touching
37112158Sdas	 * memory.
38112158Sdas	 */
39112158Sdas	return  ( (x << 56) & 0xff00000000000000UL ) |
40112158Sdas		( (x << 40) & 0x00ff000000000000UL ) |
41112158Sdas		( (x << 24) & 0x0000ff0000000000UL ) |
42112158Sdas		( (x <<  8) & 0x000000ff00000000UL ) |
43112158Sdas		( (x >>  8) & 0x00000000ff000000UL ) |
44112158Sdas		( (x >> 24) & 0x0000000000ff0000UL ) |
45112158Sdas		( (x >> 40) & 0x000000000000ff00UL ) |
46112158Sdas		( (x >> 56) & 0x00000000000000ffUL );
47112158Sdas#else
48112158Sdas	/*
49112158Sdas	 * Split the operation in two 32bit steps.
50112158Sdas	 */
51112158Sdas	u_int32_t tl, th;
52112158Sdas
53112158Sdas	th = bswap32((u_int32_t)(x & 0x00000000ffffffffULL));
54112158Sdas	tl = bswap32((u_int32_t)((x >> 32) & 0x00000000ffffffffULL));
55112158Sdas	return ((u_int64_t)th << 32) | tl;
56112158Sdas#endif
57112158Sdas}
58112158Sdas