Advertisement
lukicdarkoo

BitWise funkcije

Jan 6th, 2014
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.88 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void printBits(short value) {
  4.     short i = sizeof(value)*8 - 1;
  5.  
  6.     for (; i >= 0; i--) {
  7.         printf("%i", (value >> i) & 1);
  8.  
  9.         if (i % 4 == 0)
  10.             printf(" ");
  11.     }
  12.     printf("\n");
  13. }
  14.  
  15. short setBit(short value, short position) {
  16.     return (value | (1 << position));
  17. }
  18.  
  19. short clearBit(short value, short position) {
  20.     return ~(1 << position) & value;
  21. }
  22.  
  23. short flipBit(short value, short position) {
  24.     return (1 << position) ^ value;
  25. }
  26.  
  27. short getBit(short value, short position) {
  28.     return ((1 << position) & value) >> position;
  29. }
  30.  
  31. int main() {
  32.     short value = 15;
  33.     printBits(value);
  34.  
  35.     value = clearBit(value, 1);
  36.     printBits(value);
  37.  
  38.     value = setBit(value, 1);
  39.     printBits(value);
  40.  
  41.     value = flipBit(value, 1);
  42.     printBits(value);
  43.  
  44.     printf("%i", getBit(value, 1));
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement