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
value
> (transduce (list 1 0 0 1 0 1) #:into into-bitstring) (bitstring 1 0 0 1 0 1)
syntax
(for/bitstring (for-clause ...) body-or-break ... body)
body : bit?
> (for/bitstring ([bit (in-list (list 1 0 0 1 0 1 0 1))]) bit) (bitstring 1 0 0 1 0 1 0 1)
syntax
(for*/bitstring (for-clause ...) body-or-break ... body)
body : bit?
> (for*/bitstring ([byte (in-bytes #"hi")] [bit (in-byte byte)]) bit) (bitstring 0 1 1 0 1 0 0 0 0 1 1 0 1 0 0 1)
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)
procedure
(sequence->bitstring seq) → bitstring?
seq : (sequence/c bit?)
> (sequence->bitstring (list 1 0 1 1)) (bitstring 1 0 1 1)
> (sequence->bitstring (vector 0 1 1 0)) (bitstring 0 1 1 0)