Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say, I have a integer like 10101, I would like to unset the third bit to get 10001; if I have 10001, I will still get 10001; how can I achieve it?

unset(int i, int j)
int i= 10101 or 10000
int j = 00100
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
508 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming that you are indexing bits from the right, this should work to unset a particular bit in value:

int mask = 1 << bitIndex;
value &= ~mask;

You can set the bit using similar code:

value |= mask;

where mask is as before. (This assumes that bit indexing starts at 0.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...