bswap64.c revision 1.1
11.1Schristos/*  $NetBSD: bswap64.c,v 1.1 2005/12/20 19:28:51 christos Exp $    */
21.1Schristos
31.1Schristos/*
41.1Schristos * Written by Manuel Bouyer <bouyer@NetBSD.org>.
51.1Schristos * Public domain.
61.1Schristos */
71.1Schristos
81.1Schristos#include <sys/cdefs.h>
91.1Schristos#if defined(LIBC_SCCS) && !defined(lint)
101.1Schristos__RCSID("$NetBSD: bswap64.c,v 1.1 2005/12/20 19:28:51 christos Exp $");
111.1Schristos#endif /* LIBC_SCCS and not lint */
121.1Schristos
131.1Schristos#include <sys/types.h>
141.1Schristos#include <machine/bswap.h>
151.1Schristos
161.1Schristos#undef bswap64
171.1Schristos
181.1Schristosu_int64_t
191.1Schristosbswap64(x)
201.1Schristos	u_int64_t x;
211.1Schristos{
221.1Schristos#ifdef _LP64
231.1Schristos	/*
241.1Schristos	 * Assume we have wide enough registers to do it without touching
251.1Schristos	 * memory.
261.1Schristos	 */
271.1Schristos	return  ( (x << 56) & 0xff00000000000000UL ) |
281.1Schristos		( (x << 40) & 0x00ff000000000000UL ) |
291.1Schristos		( (x << 24) & 0x0000ff0000000000UL ) |
301.1Schristos		( (x <<  8) & 0x000000ff00000000UL ) |
311.1Schristos		( (x >>  8) & 0x00000000ff000000UL ) |
321.1Schristos		( (x >> 24) & 0x0000000000ff0000UL ) |
331.1Schristos		( (x >> 40) & 0x000000000000ff00UL ) |
341.1Schristos		( (x >> 56) & 0x00000000000000ffUL );
351.1Schristos#else
361.1Schristos	/*
371.1Schristos	 * Split the operation in two 32bit steps.
381.1Schristos	 */
391.1Schristos	u_int32_t tl, th;
401.1Schristos
411.1Schristos	th = bswap32((u_int32_t)(x & 0x00000000ffffffffULL));
421.1Schristos	tl = bswap32((u_int32_t)((x >> 32) & 0x00000000ffffffffULL));
431.1Schristos	return ((u_int64_t)th << 32) | tl;
441.1Schristos#endif
451.1Schristos}
46