Bit
Work with 32-bit values using arithmetic, bitwise operators, shifts, rotations, and hexadecimal conversion. The bit library is enabled by default.
Functions
bit.arshiftShift right while copying the original sign bit into the newly opened high positions. This preserves the sign pattern of a signed 32-bit value, though the result is still returned as unsigned.
bit.baddAdd several 32-bit values, wrapping after the highest bit. Use it when a binary format defines a running counter or checksum as unsigned 32-bit arithmetic.
bit.bandKeep only bits present in every supplied 32-bit value. A mask is a common way to test or clear named flags in a packed integer.
bit.bdivDivide successive 32-bit values using integer division. It is useful when interpreting packed counts where fractional values have no meaning.
bit.bmulMultiply values while keeping only the low 32 bits of the result. This is useful for code that must match a 32-bit binary checksum or file-format calculation.
bit.bnotInvert all 32 bits of a number. The returned value is unsigned, so the complement of zero is 4294967295 rather than -1.
bit.borCombine the bits set in any supplied 32-bit value. Use OR to turn on one or more flags without discarding the others.
bit.bsubSubtract values from left to right in unsigned 32-bit arithmetic. The first valid number starts the calculation, and a negative mathematical answer wraps into the unsigned range.
bit.bswapReverse the order of a number’s four bytes. Use it when a 32-bit value arrives in the opposite byte order from the one your binary format expects.
bit.bxorSet bits that differ between successive 32-bit values. XOR is useful for toggling flags or comparing packed values at the bit level.
bit.lshiftShift a 32-bit value left and discard bits that pass bit 31. Zero bits enter from the right.
bit.rolRotate the low 32 bits to the left, wrapping the bit that leaves the high end back to the low end. This is useful in binary algorithms that require a fixed-width rotation.
bit.rorRotate the low 32 bits to the right: bits shifted off the low end return at the high end. Rotations preserve the number of set bits.
bit.rshiftShift a 32-bit value right and fill the newly opened high bits with zero. Choose this for unsigned fields and packed masks.
bit.tobitNormalize a number to the unsigned 32-bit value used by this library. Use it before comparing a value that may have come from signed arithmetic or a larger numeric range.
bit.tohexShow the unsigned 32-bit representation of a number as lowercase hexadecimal. It is convenient when inspecting flags, packet fields, or the result of a byte swap.