Wolfram Computation Meets Knowledge

BitFlip

Contributed by: Arnoud Buzing

Flip an individual bit in an integer (0 to 1, and 1 to 0)

ResourceFunction["BitFlip"][n,p]

flips the pth bit of integer n.

Details and Options

The lowest bit of integer n (e.g. signifying 20) is flipped with p=0.

Examples

Basic Examples

Flip the 0th bit of the number 2, from a zero to a one:

In[1]:=
ResourceFunction["BitFlip"][2, 0]
Out[1]=

Flip the 0th bit of the number 3, from a one to a zero:

In[2]:=
ResourceFunction["BitFlip"][3, 0]
Out[2]=

Starting with the number zero, flip positional bits:

In[3]:=
Table[ResourceFunction["BitFlip"][0, i], {i, 0, 7}]
Out[3]=

Scope

Flip the bit associated with 24:

In[4]:=
n = RandomInteger[256 - 1];
Grid[IntegerDigits[#, 2, 8] & /@ {n, ResourceFunction["BitFlip"][n, 4]}]
Out[5]=

Flip the bit associated with 27:

In[6]:=
n = RandomInteger[256 - 1];
Grid[IntegerDigits[#, 2, 8] & /@ {n, ResourceFunction["BitFlip"][n, 7]}]
Out[7]=

Applications

Compute the Hamming-distance between a random integer and the same number with a single random bit flipped:

In[8]:=
n = RandomInteger[2^256 - 1];
HammingDistance[
 IntegerDigits[n, 2, 256],
 IntegerDigits[ResourceFunction["BitFlip"][n, RandomInteger[256]], 2, 256]
 ]
Out[12]=

Resource History