As the title suggests, this module provides an object called a CBuffer which exposes API allowing for bit-level control of a buffer’s data. You can read or write any number of bits you like (between 1 and 32 inclusive) without the boundaries of bytes getting in your way. This object is especially useful for network data compression algorithms that incorporate bit-packing.
The CBuffer has a cursor position and reading or writing to the CBuffer will advance the cursor forward unless a start position is manually supplied to those methods. Trying to read or write things out of bounds of the buffer will throw an error.
The read and write operations are limited to a maximum of 32 bit numbers, as roblox doesn’t provide libraries to perform bitwise operations on numbers larger than that. A hacky workaround is possible with intermediate buffers, but I imagine not many people will be needing to read or write something like a 45-bit number.
Constructors:
CBuffer.new(n : number) -> CBuffer
creates a new empty CBuffer that isn
bytes long
CBuffer.fromBuffer(b : buffer) -> CBuffer
Creates a new CBuffer that usesb
as its internal buffer.Properties:
cursor : number
- The cursor position in bits. A position of zero points to the first bit in the buffer.
rawBuffer : buffer
- the actual buffer object being written to.
sizeInBits : number
- the number of bits in the buffer. Is always a multiple of 8.Methods:
writeUnsignedBits(data : number, n : number, position : number?) -> ()
Copies the firstn
bits fromdata
into a space in the buffer beginning atposition
. If noposition
is provided, it begins at the cursor position and advances the cursor forwardn
bits.data
is expected to be an unsigned integer.
readUnsignedBits(n : number, position : number?) -> number
Reads the nextn
bits beginning atposition
and returns them as an unsigned integer. If noposition
is provided, it begins at the cursor position and advances the cursor forwardn
bits.
setCursor(cursorPos : number) -> ()
Places the cursor at the specified bit index in the buffer’s memory. The cursor may range from 0 toCBuffer.sizeInBits
- 1, i.e. a cursor position of zero points to the first bit in the buffer.
The lua file can be downloaded here:
cbuffer.lua (3.8 KB)