How to Set, Clear, and Toggle a Single Bit

How do I set, clear, and toggle a single bit?

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1UL << n;

That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit.

Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long. The same applies to all the rest of the examples.

Clearing a bit

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

number &= ~(1UL << n);

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

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1UL << n;

That will toggle the nth bit of number.

Checking a bit

You didn't ask for this, but I might as well add it.

To check a bit, shift the number n to the right, then bitwise AND it:

bit = (number >> n) & 1U;

That will put the value of the nth bit of number into the variable bit.

Changing the nth bit to x

Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:

number ^= (-x ^ number) & (1UL << n);

Bit n will be set if x is 1, and cleared if x is 0. If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1.

To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.

number ^= (-(unsigned long)x ^ number) & (1UL << n);

or

unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);

It's generally a good idea to use unsigned types for portable bit manipulation.

or

number = (number & ~(1UL << n)) | (x << n);

(number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x.

It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.

How do you set, clear and toggle a single bit in JavaScript?

To get a bit mask:

var mask = 1 << 5; // gets the 6th bit

To test if a bit is set:

if ((n & mask) != 0) {
// bit is set
} else {
// bit is not set
}

To set a bit:

n |= mask;

To clear a bit:

n &= ~mask;

To toggle a bit:

n ^= mask;

Refer to the Javascript bitwise operators.

How do you set, clear, and toggle a single bit in TCL?

Assuming we're talking about toggling a single bit in a value encoded as an integer, it's easy. These are all the classic ways of doing bit manipulation (and you'd do something pretty much equivalent in lots of other languages too):

proc setBit {var bit} {
upvar 1 $var v
# OR
set v [expr {$v | (1 << $bit)}]
}
proc clearBit {var bit} {
upvar 1 $var v
# AND NOT
set v [expr {$v & ~(1 << $bit)}]
}
proc toggleBit {var bit} {
upvar 1 $var v
# XOR
set v [expr {$v ^ (1 << $bit)}]
}
proc testBit {var bit} {
upvar 1 $var v
# select with AND and test
return [expr {($v & (1 << $bit)) != 0}]
}
proc setBitTo {var bit value} {
upvar 1 $var v
set v [expr {$value ? $v | (1 << $bit) : $v & ~(1 << $bit)}]
}

Note that there's no maximum size of integers in current Tcl releases (storage is expanded to whatever space is needed). Things up to the size of a machine word are merely more efficient.

You can also use binary scan to convert chunks of data into strings of 0 and 1 and do string operations on that before using binary format to convert back, but it's actually more awkward.

How do you set, clear and toggle a single bit in Rust?

Like many other languages, the bitwise operators & (bitwise AND), | (bitwise OR), ^ (bitwise XOR) exist:

fn main() {
let mut byte: u8 = 0b0000_0000;

byte |= 0b0000_1000; // Set a bit
println!("0b{:08b}", byte);

byte &= 0b1111_0111; // Unset a bit
println!("0b{:08b}", byte);

byte ^= 0b0000_1000; // Toggle a bit
println!("0b{:08b}", byte);
}

The main difference from other languages is in bitwise NOT, which uses ! instead of ~:

fn main() {
let mut byte: u8 = 0b0000_0000;

byte = !byte; // Flip all bits
println!("0b{:08b}", byte);
}

You can also shift bits left or right:

fn main() {
let mut byte: u8 = 0b0000_1000;

byte <<= 1; // shift left one bit
println!("0b{:08b}", byte);

byte >>= 1; // shift right one bit
println!("0b{:08b}", byte);
}

There are many other conceptual things that ultimately do bit-level manipulation that are not expressed with operators. Check out the documentation for an integer for examples. One interesting example is leading_zeros. Here is how to rotate by a certain number of bits:

fn main() {
let mut byte: u8 = 0b1000_0000;

byte = byte.rotate_left(1); // rotate left one bit
println!("0b{:08b}", byte);

byte = byte.rotate_right(1); // rotate right one bit
println!("0b{:08b}", byte);
}

The book has some more information

Set the i-th bit to zero? [duplicate]

You just have to replace the logical OR with a logical AND operation. You would use the & operator for that:

pt = pt & ~(1 << i);

You have to invert your mask because logical ANDing with a 1 will maintain the bit while 0 will clear it... so you'd need to specify a 0 in the location that you want to clear. Specifically, doing 1 << i will give you a mask that is 000...010..000 where the 1 is in the bit position that you want, and inverting this will give 111...101...111. Logical ANDing with this will clear the bit that you want.

How would you set and clear a single bit in Go?

Here's a function to set a bit. First, shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then OR it with the original input. This leaves the other bits unaffected but will always set the target bit to 1.

// Sets the bit at pos in the integer n.
func setBit(n int, pos uint) int {
n |= (1 << pos)
return n
}

Here's a function to clear a bit. First shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then flip every bit in the mask with the ^ operator (so 0010 becomes 1101). Then use a bitwise AND, which doesn't touch the numbers AND'ed with 1, but which will unset the value in the mask which is set to 0.

// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
mask := ^(1 << pos)
n &= mask
return n
}

Finally here's a function to check whether a bit is set. Shift the number 1 the specified number of spaces (so it becomes 0010, 0100, etc) and then AND it with the target number. If the resulting number is greater than 0 (it'll be 1, 2, 4, 8, etc) then the bit is set.

func hasBit(n int, pos uint) bool {
val := n & (1 << pos)
return (val > 0)
}

Combine Set, Clear and Toggle in one line of C

It's simply this

x = (((x & 0xD5) | 0x51) ^ 0x84)

Your first try is wrong, because the values of x are not updated so all the operations work on the same value, besides oring the values is not equivalent to assigning the result of the operation to x.

The second, is wrong because or operator precedence, so you just need parentheses.

How do I set or clear the first 3 bits using bitwise operations?

You have the bit setting correct: OR with the mask of the bits you want to set.

Bit clearing bits is very similar: AND with the ones-complement of the bits you want cleared.

Example: Word of 0x0448.

Settings bits 1, 2 and 3 would be Word OR 0x000e:

    0000 0100 0100 1000 = 0x0448
OR 0000 0000 0000 1110 = 0x000e
---- ---- ---- ----
= 0000 0100 0100 1110 = 0x044e

Clearing bits 1, 2 and 3 would be Word AND 0xfff1:

    0000 0100 0100 1000 = 0x0448
AND 1111 1111 1111 0001 = 0xfff1
---- ---- ---- ----
= 0000 0100 0100 0000 = 0x0440

Elaborating on the ones-complement, the AND pattern for clearing is the logical NOT of the OR pattern for setting (each bit reveresed):

 OR 0000 0000 0000 1110 = 0x000e
AND 1111 1111 1111 0001 = 0xfff1

so you can use your favorite language NOT operation instead of having to figure out both values.

How to set and clear different bits with a single line of code (C)

It's not possible in a single instruction. This is because there are 3 possible operations you need to do on the different bits:

  • Set them (bit 3)
  • Clear them (bit 4)
  • Leave them alone (all the other bits)

How can you select from one of three possibilities with a bitmask made up of binary digits?

Of course, you can do it with one line e.g:

data = (data | (1 << 3)) & ~(1 << 4)

Bit set/clear in C?

Assuming value is 0 or 1:

REG = (REG & ~(1 << pin)) | (value << pin);

I use REG instead of register because as @KerrekSB pointed out in OP comments, register is a C keyword.

The idea here is we compute a value of REG with the specified bit cleared and then depending on value we set the bit.



Related Topics



Leave a reply



Submit