From abe4edc419c49ba7bbe8c2d1db574761aa94c898 Mon Sep 17 00:00:00 2001 From: Ahmet Inan Date: Sat, 22 Sep 2018 19:13:37 +0200 Subject: [PATCH] added bit manipulation helpers --- README.md | 4 ++++ bitman.hh | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 bitman.hh diff --git a/README.md b/README.md index c07b5f3..ff3e97a 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,10 @@ Here a [Pseudorandom number generator](https://en.wikipedia.org/wiki/Pseudorando When dealing with unaligned and arbitrary-bit-sized elements in a data stream, the bitwise stream container might help avoiding some headaches. +### [bitman.hh](bitman.hh) + +Simple bit manipulation on byte arrays. + ### [galois_field.hh](galois_field.hh) We have to thank [Évariste Galois](https://en.wikipedia.org/wiki/%C3%89variste_Galois) for his contribution of the [Finite field](https://en.wikipedia.org/wiki/Finite_field) to mathematics, which laid the cornerstone for a variety of applications that we take for granted today. diff --git a/bitman.hh b/bitman.hh new file mode 100644 index 0000000..074841b --- /dev/null +++ b/bitman.hh @@ -0,0 +1,45 @@ +/* +Bit manipulation of byte arrays + +Copyright 2018 Ahmet Inan +*/ + +#ifndef BITMAN_HH +#define BITMAN_HH + +namespace CODE { + +void xor_be_bit(uint8_t *buf, int pos, bool val) +{ + buf[pos/8] ^= val<<(7-pos%8); +} + +void xor_le_bit(uint8_t *buf, int pos, bool val) +{ + buf[pos/8] ^= val<<(pos%8); +} + +void set_be_bit(uint8_t *buf, int pos, bool val) +{ + buf[pos/8] = (~(1<<(7-pos%8))&buf[pos/8])|(val<<(7-pos%8)); +} + +void set_le_bit(uint8_t *buf, int pos, bool val) +{ + buf[pos/8] = (~(1<<(pos%8))&buf[pos/8])|(val<<(pos%8)); +} + +bool get_be_bit(uint8_t *buf, int pos) +{ + return (buf[pos/8]>>(7-pos%8))&1; +} + +bool get_le_bit(uint8_t *buf, int pos) +{ + return (buf[pos/8]>>(pos%8))&1; +} + +} + +#endif +