6.2 Bitstrings
(require rebellion/binary/bitstring) | package: rebellion |
A bitstring is an immutable, contiguous sequence of bits . Bitstrings are represented compactly; a bitstring of 8N bits consumes N bytes of memory, plus some constant overhead. Bitstrings implement the sequence interface.
procedure
(bitstring? v) → boolean?
v : any/c
procedure
(bitstring b ...) → bitstring?
b : bit?
> (bitstring 1 0 0 1 0) (bitstring 1 0 0 1 0)
> (bitstring 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 1) (bitstring 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 1)
> (bitstring) (bitstring)
value
procedure
(bitstring-ref bits pos) → bit?
bits : bitstring? pos : (integer-in 0 (bitstring-size bits))
> (define bits (bitstring 1 1 1 0 0 1 0 0 0 1 1)) > (bitstring-ref bits 0) 1
> (bitstring-ref bits 5) 1
> (bitstring-ref bits 6) 0
> (bitstring-ref bits 8) 0
procedure
(bitstring-size bits) → natural?
bits : bitstring?
> (bitstring-size (bitstring)) 0
> (bitstring-size (bitstring 1 1 1 1 0 0 0 0)) 8
> (bitstring-size (bitstring 1 1 1 1 0 0 0 0 1)) 9
procedure
(in-bitstring bits) → (sequence/c bit?)
bits : bitstring?
> (for ([position (in-naturals)] [bit (in-bitstring (bitstring 1 1 0 0 1 0 1 0 0 1))] #:unless (zero? bit)) (printf "Bit ~a is set\n" position))
Bit 0 is set
Bit 1 is set
Bit 4 is set
Bit 6 is set
Bit 9 is set
procedure
(bitstring->padded-bytes bits) → immutable-bytes?
bits : bitstring?
> (bitstring->padded-bytes (bitstring 0 0 0 0 0 1 1 1)) #"\a"
> (bitstring->padded-bytes (bitstring 0 0 0 0 0 1 1 1 1)) #"\a\200"
procedure
(bytes->bitstring bstr [#:padding padding]) → bitstring?
bstr : immutable-bytes? padding : (integer-in 0 7) = 0
> (bytes->bitstring #"apple")
(bitstring
0
1
1
0
0
0
0
1
0
1
1
1
0
0
0
0
0
1
1
1
0
0
0
0
0
1
1
0
1
1
0
0
0
1
1
0
0
1
0
1)
> (bytes->bitstring #"Apple")
(bitstring
0
1
0
0
0
0
0
1
0
1
1
1
0
0
0
0
0
1
1
1
0
0
0
0
0
1
1
0
1
1
0
0
0
1
1
0
0
1
0
1)