Writing Macro C

I need to write a macro that receives some variable as a parameter, and for each two consecutive bits with a "1" value, replace it with 0 bits.

For example: 10110100 will become 10000100.
And, 11110000-> 00000000
11100000-> 100000000

I'm having trouble writing this macro. I tried to write a macro that receives the wach bit and replaces it if the next bit is the same (and they are both 1), but it only works for 8 bits and it is very unfriendly ...

PS I need a macro because I am learning C, and this is an exercise that I found, and I could not solve it myself. I know that I can use a function to make it easy ... but I want to know how to do it with macros.

Thank!

+3
source share
4 answers
#define foo(x,i) (((x) & (3<<i)) == (3<<i)) ? ((x) - (3 << i)) : (x)
#define clear_11(x) foo(foo(foo(foo(foo(foo(foo(foo(foo(x,8),7),6),5),4),3),2),1),0)

This will do the job. However, the extension is quite large, and compilation may take some time. So do not try this at work;)

+1
source
#define clear_bit_pairs(_x) ((_x)&~(((_x)&((_x)>>1))*3))
0
source
#define clear_bit_pairs(_x) ((_x) ^ ((((_x)&((_x)>>1))<<1) | ((_x)&((_x)>>1))) )

, . "1", . , 11100000 00000000, 111 .

0
#define foo(x) ({ \
    typeof(x) _y_ = x; \
    for(int _i_ = 0; _i_ < (sizeof(typeof(x)) << 3) + 1; _i_++) { \
        if((_y_ >> _i_ & 3) == 3) { \
            _y_ &= ~(3 << _i_); \
        } \
    } \
    _y_; \
})

, GCC, . , , , . , .: -)

, . - . , . ( , .)

-1

Source: https://habr.com/ru/post/1741253/


All Articles