Skip to content

Instantly share code, notes, and snippets.

@kimhoki
Created June 16, 2015 10:35
Show Gist options
  • Save kimhoki/34711cd67066337e0c01 to your computer and use it in GitHub Desktop.
Save kimhoki/34711cd67066337e0c01 to your computer and use it in GitHub Desktop.
그리고 리눅스 스케줄링에 사용된 비트 필드와 likely, unlikely
#include <stdio.h>
#include <string.h>
int ffs(int x)
{
int r = 1;
if(!x)
return 0;
if(!(x & 0xffff))
{
x >>= 16;
r += 16;
}
if(!(x & 0xff)){
x>>= 8;
r += 8;
}
if(!(x & 0xf)){
r >>= 4;
r += 4;
}
if(!(x & 3)){
x>>=2;
r+=2;
}
if(!(x &1)){
x >>=1;
r += 1;
}
return r;
}
#define likely(x) __builtin_expect(!!(x),1)
#define unlikely(x) __builtin_expect(!!(x),0)
#define BITS_PER_LONG 32
int sched_find_bit(const unsigned long *b)
{
#if BIT_PER_LONG == 64
if(unlikely(b[0]))
return ffs(b[0]);
if(likely(b[1]))
return ffs(b[1])+64;
return ffs(b[2])+128;
#elif BITS_PER_LONG == 32
if(unlikely(b[0]))
return ffs(b[0]);
if(unlikely(b[1]))
return ffs(b[1])+32;
if(unlikely(b[2]))
return ffs(b[0])+64;
if(b[3])
return ffs(b[3])+96;
return ffs(b[4]) + 128;
#else
#error BIT_PER_LONG not defined
#endif
}
int main()
{
unsigned short i = 0x800;
unsigned long j = 0x10000000;
int ret;
ret = ffs(i);
printf("ret: %d\n", ret);
ret = sched_find_bit(&j);
printf("ret: %d\n",ret);
printf("ret: %d\n",1<<ret);
return 0;
}

비트 필드

  1. 배열 상의 특정 비트 필드를 가지고 오기
  2. 주소 상의 특정 비트 필드를 가지고 오기
  3. likely와 unlikely
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment