Lua API:Bit

From The Powder Toy
Revision as of 20:02, 1 September 2012 by Simon (talk | contribs) (Bit API)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The Bit API provides functions for performing bitwise operations on integer numbers, the Bit API is from the LuaJIT BitOp library, documentation is copied from here

If you are unfamiliar with bitwise operations, you may want to check the Wikipedia page on the subject:



number bit.tobit(number input)

Normalizes a number to the numeric range for bit operations and returns it. This function is usually not needed since all bit operations already normalize all of their input arguments.


string bit.tohex(number input, [number length = 8])

Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used. The default is to generate 8 lowercase hex digits.


number bit.bnot(number input)

Returns the bitwise not of its argument., bit.bor, bit.bxor

number bit.bor(number input, [number input...])
number input, [number input...])
number bit.bxor(number input, [number input...])

Returns either the bitwise or, bitwise and, or bitwise xor of all of its arguments. Note that more than two arguments are allowed.

bit.lshift, bit.rshift, bit.arshift

number bit.lshift(number input, number shift)
number bit.rshift(number input, number shift)
number bit.arshift(number input, number shift)

Returns either the bitwise logical left-shift, bitwise logical right-shift, or bitwise arithmetic right-shift of its first argument by the number of bits given by the second argument. Logical shifts treat the first argument as an unsigned number and shift in 0-bits. Arithmetic right-shift treats the most-significant bit as a sign bit and replicates it. Only the lower 5 bits of the shift count are used (reduces to the range [0..31]).

bit.rol, bit.ror

number bit.rol(number input, number bits)
number bit.ror(number input, number bits)

Returns either the bitwise left rotation, or bitwise right rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side. Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).


number bit.bswap(number input)

Swaps the bytes of its argument and returns it. This can be used to convert little-endian 32 bit numbers to big-endian 32 bit numbers or vice versa.