11.3Scegger/*  $NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger 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.3Scegger__RCSID("$NetBSD: bswap64.c,v 1.3 2009/03/16 05:59:21 cegger 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.2Sapbuint64_t
191.3Sceggerbswap64(uint64_t x)
201.1Schristos{
211.1Schristos#ifdef _LP64
221.1Schristos	/*
231.1Schristos	 * Assume we have wide enough registers to do it without touching
241.1Schristos	 * memory.
251.1Schristos	 */
261.1Schristos	return  ( (x << 56) & 0xff00000000000000UL ) |
271.1Schristos		( (x << 40) & 0x00ff000000000000UL ) |
281.1Schristos		( (x << 24) & 0x0000ff0000000000UL ) |
291.1Schristos		( (x <<  8) & 0x000000ff00000000UL ) |
301.1Schristos		( (x >>  8) & 0x00000000ff000000UL ) |
311.1Schristos		( (x >> 24) & 0x0000000000ff0000UL ) |
321.1Schristos		( (x >> 40) & 0x000000000000ff00UL ) |
331.1Schristos		( (x >> 56) & 0x00000000000000ffUL );
341.1Schristos#else
351.1Schristos	/*
361.1Schristos	 * Split the operation in two 32bit steps.
371.1Schristos	 */
381.2Sapb	uint32_t tl, th;
391.1Schristos
401.2Sapb	th = bswap32((uint32_t)(x & 0x00000000ffffffffULL));
411.2Sapb	tl = bswap32((uint32_t)((x >> 32) & 0x00000000ffffffffULL));
421.2Sapb	return ((uint64_t)th << 32) | tl;
431.1Schristos#endif
441.1Schristos}
45