aboutsummaryrefslogblamecommitdiff
path: root/2.6.c
blob: 23ce1e60eb27a59416585eef52f8240e91d3e30b (plain) (tree)














































                                                                                      
#include <stdio.h>

#define INT_NBITS 32

unsigned getbits(unsigned x, int from, int to);
void pbits(int x);
unsigned setbits(unsigned x, int from, int to, int source);

int 
main(void)
{
  int x = 423834583;
  int y = 354543434;

  pbits(x);
  pbits(y);

  pbits(setbits(x, 12, 5, y));
  
  return 0;
}

unsigned 
getbits(unsigned x, int from, int to)
{
  return (x >> (from+1-to)) & ~(~(unsigned)0 << to);
}

void 
pbits(int x)
{
  for (int i = INT_NBITS-1; i >= 0; i--) {
    if (i%4 == 3)
      printf(" ");

    printf("%u", getbits(x, i, 1));
  }

  printf("\n");
}

unsigned 
setbits(unsigned x, int from, int to, int source)
{
  int model = ((((unsigned)~0 << (INT_NBITS-from)) >> (INT_NBITS - (from+to))) << to);
  return (x & ~model) | (source & model);
}