aboutsummaryrefslogtreecommitdiff
path: root/src/bits.c
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2024-05-24 13:24:27 +0300
committerKimplul <kimi.h.kuparinen@gmail.com>2024-05-24 18:13:43 +0300
commitbc600ecc3bdf0f189861dfb840f70c2339a7a853 (patch)
treed9840b1dc1b865442a028c03ad7109ac67894f6e /src/bits.c
parent6a7073e5f262db9a4578ff00b5b28e34335564ce (diff)
downloadkmi-bc600ecc3bdf0f189861dfb840f70c2339a7a853.tar.gz
kmi-bc600ecc3bdf0f189861dfb840f70c2339a7a853.zip
rename common to src
+ I keep starting to type src and wondering why autocomplete won't work, I guess src is just uncounciously a better name
Diffstat (limited to 'src/bits.c')
-rw-r--r--src/bits.c62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/bits.c b/src/bits.c
new file mode 100644
index 0000000..6462d21
--- /dev/null
+++ b/src/bits.c
@@ -0,0 +1,62 @@
+/* SPDX-License-Identifier: copyleft-next-0.3.1 */
+/* Copyright 2021 - 2022, Kim Kuparinen < kimi.h.kuparinen@gmail.com > */
+
+/**
+ * @file bits.c
+ * Bit manipulation helper implementations, currently just byte swaps.
+ */
+
+#include <kmi/types.h>
+#include <kmi/attrs.h>
+#include <kmi/bits.h>
+#include <kmi/builtin.h>
+
+#undef __bswap16
+__weak uint16_t __bswap16(const uint16_t u)
+{
+ return (u & 0xff00) >> 8 | (u & 0x00ff) << 8;
+}
+
+#undef __bswap32
+__weak uint32_t __bswap32(const uint32_t u)
+{
+ return (u & 0xff000000) >> 24 | (u & 0x00ff0000) >> 8 |
+ (u & 0x0000ff00) << 8 | (u & 0x000000ff) << 24;
+}
+
+#undef __bswap64
+__weak uint64_t __bswap64(const uint64_t u)
+{
+ return (u & 0xff00000000000000ULL) >> 56 |
+ (u & 0x00ff000000000000ULL) >> 40 |
+ (u & 0x0000ff0000000000ULL) >> 24 |
+ (u & 0x000000ff00000000ULL) >> 8 |
+ (u & 0x00000000ff000000ULL) << 8 |
+ (u & 0x0000000000ff0000ULL) << 24 |
+ (u & 0x000000000000ff00ULL) << 40 |
+ (u & 0x00000000000000ffULL) << 56;
+}
+
+#undef ffs
+__weak int ffs(int v)
+{
+ /* http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightParallel */
+ if (v == 0)
+ return 0;
+
+ /* silence ubsan warning */
+ if (v == INT_MIN)
+ return 32;
+
+ int c = 32;
+ v &= -v;
+
+ if (v) c--;
+ if (v & 0x0000FFFF) c -= 16;
+ if (v & 0x00FF00FF) c -= 8;
+ if (v & 0x0F0F0F0F) c -= 4;
+ if (v & 0x33333333) c -= 2;
+ if (v & 0x55555555) c -= 1;
+
+ return c + 1;
+}