Guest User

Untitled

a guest
Feb 18th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef unsigned int uint32;
  5. typedef unsigned long long uint64;
  6.  
  7. uint64 nearest_power_of_2(uint32 n);
  8.  
  9. int main(int argc, char* argv[])
  10. {
  11.     if (argc < 2) {
  12.         printf("usage %s integer\n", argv[0]);
  13.         return -1;
  14.     }
  15.  
  16.     uint32 n = atoi(argv[1]);
  17.  
  18.     printf("Input: %u\nNearest power of 2: %llu\n", n,
  19.         nearest_power_of_2(n));
  20.  
  21.     return 0;
  22. }
  23.  
  24. uint64
  25. nearest_power_of_2(uint32 n)
  26. {
  27.     uint32 i;
  28.  
  29.     if (n == 0)
  30.         return 0;
  31.  
  32.     for (i = 31; i > 0; i--) {
  33.         if (n > (1UL << i))
  34.             return 1UL << (i + 1);
  35.     }
  36.  
  37.     return n;
  38. }
Add Comment
Please, Sign In to add comment