Friday 29 March 2013

Bits and Bytes

I completed these a while ago and but forgot to post it. I haven't completed the Bits class yet but I have finished all the functions.


void copyBits(unsigned int& V, int bitNo, int NoOfBits, unsigned int mask){
  unsigned int m;
  for(int x=1, m=1<<bitNo; x<=NoOfBits; x++, m<<=1){
    setBit(V,(bitNo+x), (mask&m)&&1);
  }
}
void setBit(unsigned int& V, int bitNo, bool value){
  if(value){
    V = V | (1<<(bitNo-1));
    }
  else{
    V = V & ~(1<<(bitNo-1));
    }
}
void prnBits(unsigned int val){
  unsigned int m = 1 << sizeof(val)*8-1;
  int count=0;
  while(m){
    if(count==4){
      printf(" ");
      count=0;
    }
    printf("%d", (val & m)&&1);
    m = m >> 1;
    count++;
  }
}
const char* bits(unsigned int val){
  const unsigned int valSize=sizeof(val)*8-1;
  char* output = new char[valSize+2];
  unsigned int m = 1 << valSize;
  int x=0;
  for(x=0;x<=valSize;x++, m = m >> 1){
    output[x]=(val & m ? '1' : '0');
  }
  output[x]='\0';
  return output;
}
void bitDump(void* address, unsigned int sizeInBytes){
  unsigned long long valSize=(sizeInBytes*8)-1;
  unsigned long m = 1 << valSize;
  long long temp = *(reinterpret_cast<long long *>(address));
  int count=0;
  unsigned long x=0;
  printf("\n");
  for(x=0;x<=valSize,m;x++, m = m >> 1){
    if(count==4){
      printf(" ");
      count=0;
    }
    printf("%d", ((temp) & m)&&1);
    count++;
  }
}

No comments:

Post a Comment