Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to set a particular bit in a variable in C

Tags:

c

Consider a variable unsigned int a; in C.

Now say I want to set any i'th bit in this variable to '1'.

Note that the variable has some value. So a=(1<<i) will not work.

a=a+(1<<i) will work,but I am looking for the fastest way. Anything??

like image 818
vipin Avatar asked Sep 02 '11 14:09

vipin


2 Answers

Bitwise or it. e.g. a |= (1<<i)

like image 119
Matt K Avatar answered Oct 01 '22 00:10

Matt K


Some useful bit manipulation macros

#define BIT_MASK(bit)             (1 << (bit))
#define SET_BIT(value,bit)        ((value) |= BIT_MASK(bit))
#define CLEAR_BIT(value,bit)      ((value) &= ~BIT_MASK(bit))
#define TEST_BIT(value,bit)       (((value) & BIT_MASK(bit)) ? 1 : 0)
like image 36
Brandon E Taylor Avatar answered Oct 01 '22 00:10

Brandon E Taylor