fork download
  1. #define BIT_POS(N) ( 1U << (N) )
  2. #define SET_FLAG(N, F) ( (N) |= (F) )
  3. #define CLR_FLAG(N, F) ( (N) &= -(F) )
  4. #define TST_FLAG(N, F) ( (N) & (F) )
  5. #define BIT_RANGE(N, M) ( BIT_POS((M)+1 - (N))-1 << (N) )
  6. #define BIT_SHIFTL(B, N) ( (unsigned)(B) << (N) )
  7. #define BIT_SHIFTR(B, N) ( (unsigned)(B) >> (N) )
  8. #define SET_MFLAG(N, F, V) ( CLR_FLAG(N, F), SET_FLAG(N, V) )
  9. #define CLR_MFLAG(N, F) ( (N) &= ~(F) )
  10. #define GET_MFLAG(N, F) ( (N) & (F) )
  11. #include <stdio.h>
  12. void main()
  13. {
  14. unsigned char ascii_char = 'A'; /* char = 8 bits only */
  15. int test_nbr = 10;
  16. printf("Starting character = %c\n", ascii_char);
  17. /* The 5th bit position determines if the character is
  18.   uppercase or lowercase.
  19.   5th bit = 0 - Uppercase
  20.   5th bit = 1 - Lowercase */
  21. printf("\nTurn 5th bit on = %c\n", SET_FLAG(ascii_char, BIT_POS(5)) );
  22. printf("Turn 5th bit off = %c\n\n", CLR_FLAG(ascii_char, BIT_POS(5)) );
  23. printf("Look at shifting bits\n");
  24. printf("=====================\n");
  25. printf("Current value = %d\n", test_nbr);
  26. printf("Shifting one position left = %d\n",
  27. test_nbr = BIT_SHIFTL(test_nbr, 1) );
  28. printf("Shifting two positions right = %d\n",
  29. BIT_SHIFTR(test_nbr, 2) );
  30. }
Runtime error #stdin #stdout 0.01s 1720KB
stdin
Standard input is empty
stdout
Starting character = A

Turn 5th bit on = a
Turn 5th bit off = `

Look at shifting bits
=====================
Current value = 10
Shifting one position left = 20
Shifting two positions right = 5