Main Content

Binary / bitwise operations in Lua with the standard bit32 library

Archive - Originally posted on "The Horse's Mouth" - 2012-04-06 16:21:16 - Graham Ellis

If you want to do bit manipulation in Lua, you can use the bit32 library (which is loaded as a table) from Lua 5.2, and it's backported to newer Lua 5.1 versions as well. Bit manipulation is particularly useful in applications where data is packed into a series of bytes - in effect an array of booleans.

Let's see some of them in use - we have the "classic" and, or, exclusive or and not:

  wizard:j graham$ lua52
  Lua 5.2.0 Copyright (C) 1994-2011 Lua.org, PUC-Rio
  > value = 0xffff0000
  > nothr = 0x00ffff00
  > = string.format("%08x",bit32.band(value,nothr))
  00ff0000
  > = string.format("%08x",bit32.bor(value,nothr))
  ffffff00
  > = string.format("%08x",bit32.bxor(value,nothr))
  ff00ff00
  > = string.format("%08x",bit32.bnot(nothr))
  ff0000ff


We have shifts and rotates:
lshift - left shift
alshift - arithmetic left shift; special consideration for sign bit
lrotate - left shift, rotating bits that fall off the end
and the equivalent right shifts too.

There's an example of some of these in use in a program [here] - combining bitwise operators with other Lua features.

The bit32 library also includes operators to extract and even replace bits - illustrated below using hex values to make it clearer to see what is happening, but you may in practise choose any boundaries.

  Lua 5.2.0 Copyright (C) 1994-2011 Lua.org, PUC-Rio
  > value = 0xfe84c372
  > = bit32.extract(value,8,4)
  3
  > = bit32.extract(value,8,8)
  > = string.format("%x",bit32.extract(value,8,8))
  c3
  > = string.format("%x",bit32.replace(value,0x95,12,8))
  fe895372