Bits and bytes
Grammar: bit-expr, bits-lit, bit-part, bits-pattern, bit-field
An integer's bits are reached with &, | and ^ — and, or and exclusive or, on two integers of one type — with ~, which flips every bit, and with << and >>, which shift the left side by a count that is unsigned or a literal, so it is never negative. Every result stays within its type's width, and &= |= ^= <<= >>= step a mut integer. They bind tighter than a comparison — x & 1 == 0 asks about x & 1 — and have no order of their own: x >> 4 & 0xF is a compile error until parentheses say which goes first. A Bool keeps &&, || and !.
0xFF and 0b1010 are hexadecimal and binary literals, and _ may sit between digits: 0xFFFF_0000.
<<...>> builds bytes and takes them apart, most significant bit first, every field as wide as its type:
<<version, length, payload>>is aUInt8[dyn]: aUInt4writes four bits, aUInt16two bytes, aStror aUInt8[]its bytes, and a literal one byte unless it says otherwise,0x0D0A: UInt16.packet is <<version: UInt4, ihl: UInt4, length: UInt16, ...rest>>reads them back. A field is a name and its type, a literal to match,_to skip, or a run of bytes whose length an earlier field read,body: UInt8[size].littleafter a field orders its bytes least significant first.- The subject is a
UInt8[], aStror an integer, and whether every field lands where it should — whole bytes, a run starting on one — is checked at compile time.
hive.conv.bytesOf(text) and hive.conv.fromBytes(bytes) cross between a Str and its bytes.
func fnv1a(text: Str): UInt32 {
mut UInt32 hash = 0x811C_9DC5
for each b in hive.conv.bytesOf(text) {
hash = (hash ^ UInt32(b)) * 0x0100_0193
}
return hash
}
proc main(): void {
UInt8 flags = 0b1100_1010
echo flags & 0x0F // 10
echo flags >> 4 // 12
echo ~flags // 53
echo fnv1a("hello") // 1335831723
UInt8[dyn] header = <<UInt4(4), UInt4(5), 0, 0x0054: UInt16>>
echo header // [69, 0, 0, 84]
if header is <<version: UInt4, ihl: UInt4, _: UInt8, length: UInt16>> {
echo "IPv{version}, {length} bytes"
}
}