fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5.  * C bitwise Operators
  6.  * 6 of them
  7.  * >> Shift Right
  8.  * << Shift Left
  9.  * ~ NOT
  10.  * & AND
  11.  * | OR
  12.  * ^ XOR
  13.  */
  14.  
  15. /*
  16.  * A char in C is guaranteed to be 1 byte.
  17.  * Look dox dir for truth tables and other stuff.
  18.  * Check https://g...content-available-to-author-only...b.com/Acry/Byte_Drawer.
  19.  */
  20.  
  21. void traverse_byte (unsigned char);
  22.  
  23. int main(int argc, char **argv)
  24. {
  25.  
  26. (void) argc;
  27. (void) argv;
  28.  
  29. printf("Hello Bits!\n\n");
  30.  
  31. // Byte unset
  32. unsigned char x=0;
  33. traverse_byte(x); // 1
  34. // 00000000
  35.  
  36. // Byte unset
  37. x=1;
  38. traverse_byte(x); // 2
  39. // 00000001
  40.  
  41. // >> Shift Left by 4
  42. x=x<<4;
  43. traverse_byte(x); // 3
  44. // 00010000
  45.  
  46. // << Shift Right by 1
  47. x=x>>1;
  48. traverse_byte(x); // 4
  49. // 00001000
  50.  
  51. // ~ NOT
  52. // Inverts Bits
  53. x=~x;
  54. traverse_byte(x); // 5
  55. // 11110111
  56.  
  57. // & AND
  58. // Both set results in set
  59. unsigned char a=0;
  60. unsigned char b=0xff;
  61. unsigned char c=a&b;
  62. traverse_byte(c); // 6
  63. // 00000000
  64.  
  65. a = 1;
  66. b = 1;
  67. c=a&b;
  68. traverse_byte(c); // 7
  69. // 00000001
  70.  
  71. // | OR
  72. // any set results in set
  73. a = 85;
  74. b = 170;
  75. c=a|b;
  76. traverse_byte(c); // 8
  77. // 11111111
  78.  
  79. // ^ XOR
  80. // either set results in set, but not both
  81. a = 213;
  82. c=a^b;
  83. traverse_byte(c); // 9
  84. // 01111111
  85.  
  86. return EXIT_SUCCESS;
  87. }
  88.  
  89. void traverse_byte(unsigned char c)
  90. {
  91. static unsigned int count = 1;
  92. printf("%d: ",count);
  93. for (int i = 0; i < 8; i++) {
  94. printf("%d", !!((c << i) & 0x80));
  95. }
  96. printf("\n\n");
  97. count++;
  98. }
  99.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Hello Bits!

1: 00000000

2: 00000001

3: 00010000

4: 00001000

5: 11110111

6: 00000000

7: 00000001

8: 11111111

9: 01111111