Advertisement
regzarr

Untitled

Oct 30th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.00 KB | None | 0 0
  1.     }
  2.     putchar('\n');
  3. }
  4.  
  5. /* 2. a) Write  a  function  that  takes  a  32-bit  unsigned
  6.  * and  returns  the  16-bit  number formed  by  the  bits  in
  7.  * even  positions.
  8.  * I.e.,  if  we  label  the  bits. 0xBA9876543210, return  the
  9.  * number  formed  by  bits0xA86420.
  10.  * b)The  same  problem,  but  place  the  bits  in  reverse  order.
  11.  */
  12.  
  13. unsigned reverseBits (unsigned n){
  14.   unsigned result = 0, bitSize = sizeof(unsigned) * 8;
  15.   int i;
  16.   for (i = 0; i < bitSize; i++){
  17.     result = result | (1 & n);
  18.     n = n >> 1;
  19.     if(i + 1 < bitSize){
  20.         result = result << 1;
  21.     }
  22.   }
  23.   return result;
  24. }
  25.  
  26. unsigned evenPositions32b (unsigned n){
  27.   unsigned result = 0;
  28.   int i;
  29.   for (i = 0; i < 16; i++){
  30.     result = result | ((1 << i) & n);
  31.     n = n >> 1;
  32.   }
  33.   return result;
  34. }
  35.  
  36. int main(){
  37.   int a = 0xAF;
  38.   printf("even positions on a reversed would be %x\n", reverseBits(evenPositions32b(a)));
  39.   printf("even positions on a would be %x", evenPositions32b(a));
  40.   return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement