The C Programming Language 2nd Edition - 2.9 Bitwise Operators

실무에서 자주 쓰이는 것이 bit 연산이다.
잘 사용하면 1byte만으로 여러가지 일을 할 수 가 있을 것이다.

책에 나온 Exercise 2-6, 2-7 을 소스 코드로 적어봤다.
getbits()는 이미 책에서 예제로 나와 있다.

Exercise 2-6. Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7. Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.


[code]
/* getbits: get n bits from position p */
unsigned int GetBits(unsigned x, int p, int n)
{
  /*gets the right-adjusted n bits of integer x starting from position p*/
  return (x >> (p-n+1)) & ~(~0 << n);
}

unsigned int SetBits(unsigned x, int p, int n, unsigned y)
{
  /*set n bits of integer x starting from position p to the right-most n bits in integer y*/
  return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))) | ((y & ~(~0 << n)) << (p + 1 - n));
}

unsigned Invert(unsigned x, int p, int n)
{
  /*Inverts n bits in x starting from position p*/
  unsigned temp = GetBits(x, p, n);
  temp = ~temp;
  return SetBits(x, p, n, temp);
}
[/code]

이올린에 북마크하기(0) 이올린에 추천하기(0)
Posted by 피넛