From 789169d70d24ff2c1c9804f0149d0508de6dfcfa Mon Sep 17 00:00:00 2001 From: Enrique Date: Mon, 6 Jan 2025 00:50:11 +0100 Subject: First upload --- bit/bit.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ bit/bit.h | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100755 bit/bit.c create mode 100755 bit/bit.h (limited to 'bit') diff --git a/bit/bit.c b/bit/bit.c new file mode 100755 index 0000000..a4924a0 --- /dev/null +++ b/bit/bit.c @@ -0,0 +1,54 @@ +#include "bit.h" + + +u64 flp2(u64 x){ + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + x |= (x >> 32); + return x - (x >> 1); +} + +u32 flp2_32(u32 x){ + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x - (x >> 1); +} + +u64 clp2(u64 x){ + x -= 1; + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + x |= (x >> 32); + return x + 1; +} + +u32 clp2_32(u32 x){ + x -= 1; + x |= (x >> 1); + x |= (x >> 2); + x |= (x >> 4); + x |= (x >> 8); + x |= (x >> 16); + return x + 1; +} + +void _bitstofile(void const * const ptr, size_t const size, FILE *fp){ + unsigned char *b = (unsigned char*)ptr; + for(int i = size-1; i >= 0; i--){ + for(int j = 7; j >= 0; j--){ + unsigned char byte = ((b[i] >> j) & 1) ? '1' : '0'; + fputc(byte, fp); + } + if(i != 0) fputc(' ', fp); + } +} + diff --git a/bit/bit.h b/bit/bit.h new file mode 100755 index 0000000..9e1b09a --- /dev/null +++ b/bit/bit.h @@ -0,0 +1,42 @@ +#ifndef BIT_H +#define BIT_H + +/* + Most of these functions are courtesy of + Hacker's Delight, 2nd edition (Henry S. Warren, Jr.) +*/ + +#include +#include "types/types.h" + + +// rounds down (floors) to the nearest power of 2 +u64 flp2(u64 x); + +// rounds down (floors) to the nearest power of 2 in 32 bits +u32 flp2_32(u32 x); + +// rounds up (ceils) to the nearest power of 2 +u64 clp2(u64 x); + +// rounds up (ceils) to the nearest power of 2 in 32 bits +u32 clp2_32(u32 x); + +// prints the bits of the data pointed to by ptr of size size to fp +void _bitstofile(void const * const ptr, size_t const size, FILE *fp); + +#define fprintb(n, f) ({ \ + typeof(n) _n = (n); \ + _bitstofile(&(_n), sizeof(_n), f); \ + }) + +#define printb(n) fprintb(n, stdout) + +#define fputb(n, f) ({ \ + fprintb(n, f); \ + fputc('\n', f); \ + }) + +#define putb(n) fputb(n, stdout) + +#endif -- cgit v1.2.3