add bswap32/bswap64

This commit is contained in:
2024-02-13 19:37:18 +01:00
parent 0e9b25dd68
commit f9aec10459
4 changed files with 92 additions and 16 deletions

View File

@@ -0,0 +1,38 @@
/* generic-bswap.h - generic bswap implementations.
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef _GENERIC_BSWAP_H_
#define _GENERIC_BSWAP_H_
#include "brlib.h"
/* Adapted from: http://www-graphics.stanford.edu/%7Eseander/bithacks.html
*/
static __always_inline u32 __bswap32_emulated(u32 n)
{
const u32 k = 0x00FF00FF;
n = ((n >> 8) & k) | ((n & k) << 8);
n = ( n >> 16) | ( n << 16);
return n;
}
static __always_inline u64 __bswap64_emulated(u64 n)
{
const u64 k1 = 0x00FF00FF00FF00FFull;
const u64 k2 = 0x0000FFFF0000FFFFull;
n = ((n >> 8) & k1) | ((n & k1) << 8);
n = ((n >> 16) & k2) | ((n & k2) << 16);
n = ( n >> 32) | ( n << 32);
return n;
}
#endif /* _GENERIC_BSWAP_H_ */

View File

@@ -16,6 +16,7 @@
#include "brlib.h"
#include "bitops-emulated/generic-ctz.h"
#include "bitops-emulated/generic-clz.h"
#include "bitops-emulated/generic-bswap.h"
#ifndef __has_builtin
#define __has_builtin(x) 0
@@ -35,7 +36,9 @@
#if __has_builtin(__builtin_ffs)
# define HAS_FFS
#endif
#if __has_builtin(__builtin_bswap32)
# define HAS_BSWAP
#endif
/**
* print_bitops_impl() - print bitops implementation.
@@ -174,6 +177,24 @@ void print_bitops_impl(void);
#define ffz32(n) ffs32(~(n))
#define ffz64(n) ffs64(~(n))
/**
* bswap32, bswap64 - reverse bytes: 0x01020304 -> 0x04030201
* @n: unsigned 32 or 64 bits integer.
*
* ffs(n) is similar to ctz(n) + 1, but returns 0 if n == 0 (except
* for ctz version, where ffs(0) is undefined).
* ffz(n) is ffz(~n), with undefine value if n = 0.
*/
#if defined(HAS_BSWAP)
# define __bswap32_native(n) __builtin_bswap32(n)
# define __bswap64_native(n) __builtin_bswap64(n)
# define bswap32(n) __bswap32_native(n)
# define bswap64(n) __bswap64_native(n)
#else
# define bswap32(n) __bswap32_emulated(n)
# define bswap64(n) __bswap64_emulated(n)
#endif
/**
* fls32, fls64 - return one plus MSB index: 00101000 -> 6
* @n: unsigned 32 or 64 bits integer.