블로그 (Blog)/개발로그 (Devlogs)

주어진 위치에서 원하는 bit 수만큼 int 타입으로 추출

ihmin 2024. 3. 7. 15:57
// extract k bits from a given position.

#include <stdio.h>
  
// Function to extract k bits from p position
// and returns the extracted value as integer
int bitExtracted(int number, int k, int p)
{
    return (((1 << k) - 1) & (number >> (p - 1)));
}
  
// Driver code
int main()
{
    int number = 171, k = 5, p = 2;
    printf("The extracted number is %d", bitExtracted(number, k, p));
    return 0;
}