As of Version 14.1, BitFlip is a built-in symbol.

Function Repository Resource:

BitFlip

Source Notebook

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

Contributed by: Arnoud Buzing

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 (3) 

Flip the 0th bit of the number 2 from a 0 to a 1:

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

Flip the 0th bit of the number 3 from a 1 to a 0:

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

Starting with the number 0, flip positional bits:

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

Scope (2) 

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 (1) 

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[8]=

Publisher

Arnoud Buzing

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 29 January 2019

License Information