training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

power2.c (641B)


      1 /* Exercise 10.12 */
      2 
      3 #include <stdio.h>
      4 
      5 typedef unsigned u_int;
      6 
      7 void pbits(u_int n);
      8 u_int power2(u_int n, int pow);
      9 
     10 int main(void)
     11 {
     12    u_int num;
     13    int pow;
     14 
     15    printf("Num and pow: ");
     16    scanf("%u%d", &num, &pow);
     17 
     18    num = power2(num, pow);
     19 
     20    printf("pbits(%u): ", num);
     21    pbits(num);
     22 
     23    printf("\n");
     24 
     25    return 0;
     26 } /* E0F main */
     27 
     28 /* Print a number in bits */
     29 void pbits(u_int n)
     30 {
     31    u_int mask = 1 << 31;
     32    int i;
     33 
     34    for(i = 1; i <= 32; i++) {
     35       printf("%u", n & mask ? 1 : 0);
     36 
     37       if( !(i % 8) )
     38 	 putchar(' ');
     39 
     40       n <<= 1;
     41    }
     42 
     43 } /* eof pbits() */
     44 
     45 u_int power2(u_int n, int pow)
     46 {
     47    return n <<= pow;
     48 }
     49