Skip to content

Instantly share code, notes, and snippets.

@shawnfeng0
Last active November 25, 2021 20:07
Show Gist options
  • Save shawnfeng0/54788ca93a5d2c26440b561b9db19062 to your computer and use it in GitHub Desktop.
Save shawnfeng0/54788ca93a5d2c26440b561b9db19062 to your computer and use it in GitHub Desktop.
Read/Write some bits within a number
/**
* Modify some bits within a number
*
* @note The lowest index is 0, increasing sequentially
*
* @param origin Original data
* @param offset Offset that needs to be modified
* @param len Bit length
* @param value The value to which the specified bit needs to be replaced
* @return Modified value
*/
static inline unsigned int WriteBits(unsigned int origin, unsigned int offset,
unsigned int len, unsigned int value) {
if (offset > sizeof(origin) * 8 - 1 || len > sizeof(origin) * 8 - 1)
return (unsigned int)-1;
unsigned mask = (1U << len) - 1;
origin &= ~(mask << offset); // Empty the location you want to edit
value &= mask; // Intercept value to the specified length
return origin | (value << offset); // merge
}
/**
* Read some bits within a number
*
* @note The lowest index is 0, increasing sequentially
*
* @param origin Original data
* @param offset Offset that needs to be read
* @param len Bit length
* @return read value
*/
static inline unsigned int ReadBits(unsigned int origin, unsigned int offset,
unsigned int len) {
if (offset > sizeof(origin) * 8 - 1 || len > sizeof(origin) * 8 - 1)
return (unsigned int)-1;
unsigned mask = (1U << len) - 1;
return (origin >> offset) & mask; // Intercept value to the specified length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment