How to unset a specific bit in an integer

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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 

回答1:

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

int mask = 1 

You can set the bit using similar code:

value |= mask; 

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



回答2:

To clear or unset a bit

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

 number &= ~(1 

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.



回答3:

If you are dealing with litterals, then you can just work with the hex numbers. Converting your bit patterns to hex numbers:

10101 => 0x15 00100 => 0x04 

So the following C code would set b to the result you want.

int a = 0x15; int b = a & ~( 0x04 ); 

If you wanted something generic you could have a C function (with all range checking removed) like

int clearBit( int value, int bit ) {     // Assume we count bits starting at 1     return value & ~( 1 


回答4:

In C and C++ use bit wise AND operator to form an AND mask:

10101 & 10001 


回答5:

You can toggle the nth bit

result = number ^ (1



回答6:

Bitwise functions.

In Java:

int num = 0b10101; int mask = 1 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!