Function Repository Resource:

BitTest

Source Notebook

Determine whether a given bit in an integer is set to one

Contributed by: Daniel Sanchez

ResourceFunction["BitTest"][n, k]

returns True if the kth (starting from zero) bit of n is set to 1 and returns False otherwise.

ResourceFunction["BitTest"][n, {k1,k2, }]

returns a list of truth values for each ki.

ResourceFunction["BitTest"][n, {k1,k2, }, op]

applies the logical operator op to the list of truth values.

Details and Options

ResourceFunction["BitTest"][{n1,n2, }, k] tests if the bit at position k is set for each ni.
ResourceFunction["BitTest"][n, k] is equivalent to BitAnd[n, 2k] > 0.
ResourceFunction["BitTest"][n, {k1,k2, }] is equivalent to ResourceFunction["BitTest"][n, {k1,k2, }, List].
ResourceFunction["BitTest"][n, {k1,k2, }, op] is equivalent to Apply[op][ResourceFunction["BitTest"][n, ki]].
The logical operators supported are And, Nand, Nor, Or and Xor.

Examples

Basic Examples (2) 

Display coefficients at powers of 2 in the integer 42:

In[1]:=
IntegerDigits[42, 2]
Out[1]=

Determine whether the bit at position 3 is set:

In[2]:=
ResourceFunction["BitTest"][42, 3]
Out[2]=

Test whether bits 0 through 5 are set:

In[3]:=
ResourceFunction["BitTest"][42, Range[0, 5]]
Out[3]=

Various logical operators can be passed down as a third argument:

In[4]:=
Table[ResourceFunction["BitTest"][2^^100001, {5, 0}, op], {op, {And, Nand, Nor, Or, Xor}}]
Out[4]=

Applications (1) 

Test whether a 4-bit register should set a carry flag after performing addition:

In[5]:=
fourBitAddition[acc_, val_] := Module[{res, carry},
  carry = False;
  res = acc + val;
  If[ResourceFunction["BitTest"][res, 4],
   res = BitAnd[res, 2^^1111];
   carry = True
   ];
  {res, carry}
  ]

fourBitAddition[14, #] & /@ {1, 2}
Out[6]=

Properties and Relations (2) 

The following are equivalent:

In[7]:=
ResourceFunction["BitTest"][42, 3] === (BitGet[42, 3] > 0) === (BitAnd[42, 2^3] > 0)
Out[7]=

The DataStructure "BitVector" has this function as one of its methods:

In[8]:=
ds = CreateDataStructure["BitVector", 8];
ds["BitSet", 5];
{ds["BitTest", 5], ds["BitTest", 6]}
Out[9]=

Publisher

Daniel Sanchez

Version History

  • 1.0.0 – 10 November 2020

Related Resources

License Information