Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unset a specific bit in an integer

Tags:

java

c++

c

c#

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
like image 575
user705414 Avatar asked Dec 19 '11 04:12

user705414


People also ask

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.

How do I unset a specific bit?

Use the bitwise AND operator (&) to clear a bit. That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it. NOTE : here x is the position of bit starting from 0 to LSB.

How do you change the nth bit of a number?

Logic to get nth bit of a number Store it in some variable say num. Input the bit position from user. Store it in some variable say n. To get the nth bit of num right shift num, n times.


2 Answers

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.)

like image 80
Ted Hopp Avatar answered Sep 19 '22 14:09

Ted Hopp


To clear or unset a bit

Use the bitwise AND operator (&) to clear a bit.

 number &= ~(1 << x); 

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

NOTE : here x is the position of bit starting from 0 to LSB.

like image 45
Jeegar Patel Avatar answered Sep 19 '22 14:09

Jeegar Patel