Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <assert.h>
- #include <limits.h>
- /*
- * Display a byte in binary format (called by debug macro below)
- */
- void debug_out(const char* name, uint8_t value)
- {
- char out[CHAR_BIT + 1];
- int i = CHAR_BIT;
- out[i--] = '\0';
- for (; i >= 0; --i) {
- int bitnum = CHAR_BIT - i - 1;
- out[i] = (value & (1 << bitnum)) ? '1' : '0';
- }
- printf("%-10s: 0b%s\n", name, out);
- }
- /*----------------------------------------------------*/
- /*
- * Debug MACRO
- */
- #if !defined(NDEBUG)
- #define DEBUG_BITS(a) do { debug_out(#a, a); } while(0)
- #else
- #define DEBUG_BITS(a) do { /**/ } while(0)
- #endif
- /*----------------------------------------------------*/
- /*
- * flip bit at location BITNUM using bitwise OR, AND
- * operation
- */
- uint8_t flip1(uint8_t bits, int bitnum)
- {
- assert(0 <= bitnum && bitnum <= 7);
- uint8_t flipped = bits;
- uint8_t single_bit = (uint8_t)(1 << bitnum);
- DEBUG_BITS(bits);
- if ((flipped & single_bit) != 0) {
- flipped &= ~single_bit;
- }
- else {
- flipped |= single_bit;
- }
- DEBUG_BITS(flipped);
- return flipped;
- }
- /*----------------------------------------------------*/
- /*
- * flip bit at location BITNUM using bitwise XOR operation
- */
- uint8_t flip2(uint8_t bits, int bitnum)
- {
- assert(0 <= bitnum && bitnum <= 7);
- uint8_t flipped = bits;
- uint8_t single_bit = (uint8_t)(1 << bitnum);
- DEBUG_BITS(bits);
- /* XOR bitwise operation */
- flipped ^= single_bit;
- DEBUG_BITS(flipped);
- return flipped;
- }
- /*----------------------------------------------------*/
- int main()
- {
- for (int value = 0; value <= 255; ++value) {
- for (int bitnum = 0; bitnum < 8; ++bitnum) {
- uint8_t f1, f2;
- printf("value = %d, bitnum = %d\n", value, bitnum);
- printf("=======================\n");
- f1 = flip1((uint8_t) value, bitnum);
- printf("\n");
- f2 = flip2((uint8_t) value, bitnum);
- assert(f1 == f2);
- printf("\n\n");
- }
- }
- }
- /*----------------------------------------------------*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement