BitfieldPacked bit manipulation types with network byte order support.

Bitfield

Packed bit manipulation types with network byte order support.

import core.bitfield

Types

Four bitfield sizes are available:

TypeBitsRange
Bitfield880-255
Bitfield16160-65535
Bitfield32320-4294967295
Bitfield64640-2^64-1

Construction

let bf = Bitfield8.new(0xFF)
let bf = Bitfield8.zero()
let bf = Bitfield8.fromBits(1, 0, 1, 1, 0, 0, 1, 0)

Convenience constructors:

let bf = bitfield8(42)
let bf = bitfield16(1024)
let bf = bitfield32(0xDEADBEEF)
let bf = bitfield64(0)

Bit Operations

All types share the same methods:

MethodReturnDescription
getBit(index: Int)IntGet bit at position (0 or 1)
setBit(index: Int, value: Int)Bitfield*Set bit, return new
getField(start: Int, length: Int)IntExtract bit field
setField(start: Int, length: Int, value: Int)Bitfield*Set bit field, return new

Bitwise Operations

MethodReturnDescription
bitwiseAnd(other: Bitfield*)Bitfield*AND
bitwiseOr(other: Bitfield*)Bitfield*OR
bitwiseXor(other: Bitfield*)Bitfield*XOR
bitwiseNot()Bitfield*NOT
shiftLeft(amount: Int)Bitfield*Left shift
shiftRight(amount: Int)Bitfield*Right shift

Bit Counting

MethodReturnDescription
countOnes()IntPopulation count
countZeros()IntZero count
leadingZeros()IntLeading zero count
trailingZeros()IntTrailing zero count

Conversion

MethodReturnDescription
toInt()IntConvert to integer
toUnsigned()IntConvert to unsigned integer
toBinaryString()StringBinary representation
toHexString()StringHexadecimal representation
toString()StringString representation

Endianness Conversion

MethodReturnDescription
toBigEndian()Bitfield*Convert to big endian
toLittleEndian()Bitfield*Convert to little endian

Network Byte Order Functions

FunctionDescription
htons(value)Host to network short (16-bit)
htonl(value)Host to network long (32-bit)
htonll(value)Host to network long long (64-bit)
ntohs(value)Network to host short
ntohl(value)Network to host long
ntohll(value)Network to host long long

Utility

fun pow2(n: Int) r: Int  // 2^n

Example

let flags = Bitfield8.zero()
let flags = flags.setBit(0, 1)  // set bit 0
let flags = flags.setBit(3, 1)  // set bit 3
println(flags.toBinaryString()) // "00001001"
println("Bit 0: {flags.getBit(0)}")  // 1
println("Ones: {flags.countOnes()}")  // 2

// Network packet header
let header = bitfield32(0)
let header = header.setField(0, 4, 6)   // version = 6
let header = header.setField(4, 8, 128) // traffic class
let network = header.toBigEndian()
Architected in Kotlin. Rendered with Materia. Powered by Aether.
© 2026 Yousef.