Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing bits in an int in C?

Tags:

c

int

bit

So I have a 16 bit number. Say that the variable name for it is Bits. I want to make it so that Bits[2:0] = 001, 100, and 000, without changing anything else. I'm not sure how to do it, because all I can think of is ORing the bit I want to be a 1 with 1, but I'm not sure how to clear the other bits so that they're 0. If anyone has advice, I'd appreciate it. Thanks!

like image 214
user2253332 Avatar asked Apr 10 '13 01:04

user2253332


1 Answers

To clear certain bits, & with the inverse of the bits to be cleared. Then you can | in the bits you want.

In this case, you want to zero out the lower three bits (111 in binary or 7 in decimal), so we & with ~7 to clear those bits.

Bits = (Bits & ~7) | 1; // set lower three bits of Bits to 001
like image 64
nneonneo Avatar answered Oct 17 '22 05:10

nneonneo