## How to modify bits in an integer?

I have an integer with a value `7`

(`0b00000111`

) And I would like to replace it with a function to `13`

(`0b00001101`

). What is the best algorithm to replace bits in an integer?

For example:

set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?

You just need:

def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the bit indicated by the mask. return v # Return the result, we're done. >>> set_bit(7, 3, 1) 15 >>> set_bit(set_bit(7, 1, 0), 3, 1) 13

Note that bit numbers (`index`

) are from 0, with 0 being the least significant bit.

Also note that the new value is *returned*, there's no way to modify an integer "in place" like you show (at least I don't think so).

**Modify a bit at a given position,** // Returns modified n. int modifyBit( int n, int p, int b). Given a number n, a position p and a binary value b, we need to change the bit at position p in n to value b. Examples : Input : n = 7, p = 2, b = 0 Output : 3 7 is 00000111 after clearing bit at 2rd position, it becomes 0000011. Input : n = 7, p = 3, b = 1 Output : 15 7 is 00000111 after setting bit at 3rd position it becomes 00001111.

These work for integers of any size, even greater than 32 bit:

def set_bit(value, bit): return value | (1<<bit) def clear_bit(value, bit): return value & ~(1<<bit)

If you like things short, you can just use:

>>> val = 0b111 >>> val |= (1<<3) >>> '{:b}'.format(val) '1111' >>> val &=~ (1<<1) '1101'

**Count set bits in an integer,** Simple Method Loop through all bits in an integer, check if a bit is set and if it is then Duration: 10:00
Posted: Oct 7, 2011 To modify the most significant bit, you need that bitmask to be set in the most-significant bit position. Get it with some bit-math and #include <limits>: T high_bit_mask = T(1) << (std::numeric_limits<T>::digits - 1) This presupposes that T is an unsigned integer type. (You should not be performing bit hacks on signed types.

You can use bitwise opertions. http://wiki.python.org/moin/BitwiseOperators

if you want to set a given bit to 1 you can use bitwise 'or' with 1 on given position:

**0b00000111** | **0b00001000** = **0b00001111**

to set a given bit to 0 you can use bitwise 'and'

**0b00001111** & **0b11111011** = **0b00001011**

Note that 0b prefix is for binary numbers and 0x is for hexadecimal.

**Set the K-th bit of a given number,** C++ implementation to set the kth bit. // of the given number. #include <bits/stdc++.h>. using namespace std;. // function to set the kth bit. int setKthBit( int n, int k). public static int setBits(int orig, int newBits, int mask) { return (orig & ~mask) | (bits & mask); } Of course, if you're being handed the RGB value as a 32 bit number, you could always convert it to a byte array and vice versa, which makes the manipulations much easier.

Going by the examples provided, it sounds like you are looking to swap bits in an integer.
For example in 7 `(0b00000111)`

, if you swap the bits in the 3rd and 1st positions you obtain 13 `(0b00001101)`

.

I would have the following as a function signature `swap_bits(val, i, j)`

What is the best algorithm? Well, the following algorithm takes constant time, O(1).

def swap_bits(val, i, j): """ Given an integer val, swap bits in positions i and j if they differ by flipping their values, i.e, select the bits to flip with a mask. Since v ^ 1 = 0 when v = 1 and 1 when v = 0, perform the flip using an XOR. """ if not (val >> i) & 1 == (val >> j) & 1: mask = (1 << i) | (1 << j) val ^= mask return val

Example:

>>> swap_bits(7, 3, 1) 13

The code leverage bit twiddling tricks and here is a good resource by Sean Anderson. I am working on providing the code snippets in Python here.

**Change bits to make specific OR value,** Given two positive integers A and B, we can change at most K bits in both the numbers to make OR of them equal to a given target number T. In the case of The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer. 1 Initialize count: = 0 2 If integer n is not zero (a) Do bitwise & with (n-1) and assign the value back to n n: = n& (n-1) (b) Increment count by 1 (c) go to step 2 3 Else return count.

**Count set bits in an integer,** Explanation for the article: http://www.geeksforgeeks.org/count-set-bits-in-an-integer/ This Duration: 10:00
Posted: Jan 8, 2017 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 maskis as before.

**Bit Twiddling Hacks,** unsigned int v; // count bits set in this (32-bit value) The best method for counting bits in a 32-bit integer v is the An INT and a DINT are the next structures we’ll explore. An INT, as the name suggests, is used to hold an integer. The structure within a PLC can be broken down into 16 distinct booleans which correlates to the fact that an integer is 16 bits. You’d create an INT just like you would a boolean.

**A Bit of Fun Fun With Bits,** However, one of the most useful and effective low-level optimizations is bit manipulation, or using the bits of an integer to represent a set. Not only does it Bits, Bytes, Bit Operations and image processing 15-123 Systems Skills in C and Unix. Representing Information • Consider a n-bit integer representation of an