Skip to content

Instantly share code, notes, and snippets.

@jledet
Created June 2, 2012 08:36
Show Gist options
  • Save jledet/2857343 to your computer and use it in GitHub Desktop.
Save jledet/2857343 to your computer and use it in GitHub Desktop.
Extract offset bits from bit field
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
uint32_t get_offset_bits(uint8_t *data, uint32_t offset, uint32_t count)
{
int shft;
uint32_t ret, byte;
byte = offset / 8;
shft = offset & 7;
ret = (((uint32_t)data[byte + 0]) << (shft + 24));
if (count + shft > 8)
ret |= (((uint32_t)data[byte + 1]) << (shft + 16));
if (count + shft > 16)
ret |= (((uint32_t)data[byte + 2]) << (shft + 8));
if (count + shft > 24)
ret |= (((uint32_t)data[byte + 3]) << (shft + 0));
if (count + shft > 32)
ret |= (((uint32_t)data[byte + 4]) << (shft - 8));
return ret >> (32 - count);
}
int main(void)
{
uint8_t test[] = {0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03};
printf("%"PRIx32"\n", get_offset_bits(test, 0, 32));
printf("%"PRIx32"\n", get_offset_bits(test, 62, 2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment