본문으로 바로가기

출처: https://stackoverflow.com/a/23021017

n bytes 에서 특정 bit 영역만 추출.

pickbits.h

#ifndef PICKBITS_H_INCLUDED
#define PICKBITS_H_INCLUDED
 
#include <stddef.h>
#include <stdint.h>
 
extern uint64_t pick_bits(unsigned char *bytes, size_t nbytes, int lo, int hi);
 
#endif /* PICKBITS_H_INCLUDED */

pickbits.c

#include "pickbits.h"
#include <assert.h>
 
uint64_t pick_bits(unsigned char *bytes, size_t nbytes, int lo, int hi)
{
  assert(bytes != 0 && nbytes > 0 && nbytes <= 8);
  assert(lo >= 0 && lo < 64);
  assert(hi >= 0 && hi < 64 && hi >= lo);
  uint64_t result = 0;
  for (int i = nbytes - 1; i >= 0; i--)
    result = (result << 8) | bytes[i];
  result >>= lo;
  result &= (UINT64_C(1) << (hi - lo + 1)) - 1;
  return result;
}

test.c

#include "pickbits.h"
#include <inttypes.h>
#include <stdio.h>
 
int main(void)
{
  unsigned char d1[8] = "\xA5\xB4\xC3\xD2\xE1\xF0\x96\x87";
  /* Selecting nybbles */
  for (int u = 0; u < 64; u += 4)
  {
    uint64_t v = pick_bits(d1, sizeof(d1), u, u+3);
    printf("Picking bits %2d..%2d gives 0x%" PRIX64 "\n", u, u+3, v);
  }
  /* Select across nybble boundaries - T.B.D */
  return 0;
}

결과

Picking bits  0.. 3 gives 0x5
Picking bits  4.. 7 gives 0xA
Picking bits  8..11 gives 0x4
Picking bits 12..15 gives 0xB
Picking bits 16..19 gives 0x3
Picking bits 20..23 gives 0xC
Picking bits 24..27 gives 0x2
Picking bits 28..31 gives 0xD
Picking bits 32..35 gives 0x1
Picking bits 36..39 gives 0xE
Picking bits 40..43 gives 0x0
Picking bits 44..47 gives 0xF
Picking bits 48..51 gives 0x6
Picking bits 52..55 gives 0x9
Picking bits 56..59 gives 0x7
Picking bits 60..63 gives 0x8