Created
September 22, 2021 14:21
-
-
Save physuru/d5200c27dde59b72d8fa6a87bd1260e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
// treated as "independent", not as part of a larger integer | |
// i.e., for the "2nd" ("index 1") bit from the left will be output as `1`, not `2` | |
static uint32_t _read_bits(uint32_t u32, uint8_t where, uint8_t len) { | |
return ((u32 & (((1 << len) - 1) << where)) >> where); | |
} | |
static void _write_bits(uint32_t *var, uint8_t where, uint32_t bits, uint8_t len) { | |
*var = ((*var & ~(len << where)) | bits << where); | |
} | |
#define convert_le_off_to_be_off_in_u32(off) ((((31 - off) / 8) * 8) + (off % 8)) | |
static uint32_t be_read_bits(uint32_t u32, uint8_t where, uint8_t len) { | |
return _read_bits(u32, convert_le_off_to_be_off_in_u32(where), len); | |
} | |
static void be_write_bits(uint32_t *var, uint8_t where, uint32_t bits, uint8_t len) { | |
return _write_bits(var, convert_le_off_to_be_off_in_u32(where), bits, len); | |
} | |
uint32_t (*read_bits)(uint32_t var, uint8_t where, uint8_t len); | |
void (*write_bits)(uint32_t *var, uint8_t where, uint32_t bits, uint8_t len); | |
void init_bit_rw_ptrs(void) { | |
uint8_t bytes[] = { 0x00, 0x01 }; | |
if (*(uint16_t *)&bytes & 1) { | |
read_bits = &be_read_bits; | |
write_bits = &be_write_bits; | |
} | |
read_bits = &_read_bits; | |
write_bits = &_write_bits; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment