Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <assert.h>
  4. #include <limits.h>
  5.  
  6. /*
  7.  *  Display a byte in binary format (called by debug macro below)
  8.  */
  9. void debug_out(const char* name, uint8_t value)
  10. {
  11.     char out[CHAR_BIT + 1];
  12.     int i = CHAR_BIT;
  13.  
  14.     out[i--] = '\0';
  15.     for (; i >= 0; --i) {
  16.         int bitnum = CHAR_BIT - i - 1;
  17.         out[i] = (value & (1 << bitnum)) ? '1' : '0';
  18.     }
  19.  
  20.     printf("%-10s: 0b%s\n", name, out);
  21. }
  22. /*----------------------------------------------------*/
  23.  
  24. /*
  25.  *  Debug MACRO
  26.  */
  27. #if !defined(NDEBUG)
  28. #define DEBUG_BITS(a) do { debug_out(#a, a); } while(0)
  29. #else
  30. #define DEBUG_BITS(a) do { /**/ } while(0)
  31. #endif
  32. /*----------------------------------------------------*/
  33.  
  34. /*
  35.  *  flip bit at location BITNUM using bitwise OR, AND
  36.  *  operation
  37.  */
  38. uint8_t flip1(uint8_t bits, int bitnum)
  39. {
  40.     assert(0 <= bitnum && bitnum <= 7);
  41.  
  42.     uint8_t flipped = bits;
  43.     uint8_t single_bit = (uint8_t)(1 << bitnum);
  44.  
  45.     DEBUG_BITS(bits);
  46.  
  47.     if ((flipped & single_bit) != 0) {
  48.         flipped &= ~single_bit;
  49.     }
  50.     else {
  51.         flipped |= single_bit;
  52.     }
  53.  
  54.     DEBUG_BITS(flipped);
  55.     return flipped;
  56. }
  57. /*----------------------------------------------------*/
  58.  
  59. /*
  60.  *  flip bit at location BITNUM using bitwise XOR operation
  61.  */
  62. uint8_t flip2(uint8_t bits, int bitnum)
  63. {
  64.     assert(0 <= bitnum && bitnum <= 7);
  65.  
  66.     uint8_t flipped = bits;
  67.     uint8_t single_bit = (uint8_t)(1 << bitnum);
  68.  
  69.     DEBUG_BITS(bits);
  70.  
  71.     /* XOR bitwise operation */
  72.     flipped ^= single_bit;
  73.  
  74.     DEBUG_BITS(flipped);
  75.     return flipped;
  76. }
  77. /*----------------------------------------------------*/
  78.  
  79. int main()
  80. {
  81.     for (int value = 0; value <= 255; ++value) {
  82.         for (int bitnum = 0; bitnum < 8; ++bitnum) {
  83.             uint8_t f1, f2;
  84.  
  85.             printf("value = %d, bitnum = %d\n", value, bitnum);
  86.             printf("=======================\n");
  87.             f1 = flip1((uint8_t) value, bitnum);
  88.             printf("\n");
  89.             f2 = flip2((uint8_t) value, bitnum);
  90.             assert(f1 == f2);
  91.             printf("\n\n");
  92.         }
  93.     }
  94. }
  95. /*----------------------------------------------------*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement