12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- (library (bytevector-utils)
- (export ascii-string->bytevector
- integer->bytevector)
- (import (except (rnrs base) let-values vector-for-each)
- (only (guile)
- lambda* λ)
- (rnrs bytevectors))
- (define ascii-string->bytevector
- (lambda* (string len #:key (endianness 'big))
- "Assuming, that string contains only ASCII characters."
- (cond
- [(eq? endianness 'big)
- (string->utf8 string)]
- [else
- (let ([bv (make-bytevector len 0)])
- (let iter
- ([index 0]
- [°char-nums (map char->integer (string->list string))])
- (cond
- [(null? °char-nums) bv]
- [else
- (bytevector-uint-set! bv
- (- (- len 1) index)
- (car °char-nums)
- endianness
- 1)
- (iter (+ index 1) (cdr °char-nums))])))])))
- (define integer->bytevector
- (lambda* (int num-bytes #:key (endianness 'big) (index 0) (signed #t))
- (let ([bv (make-bytevector num-bytes)])
- (cond
- [signed
- (bytevector-sint-set! bv 0 int endianness num-bytes)]
- [else
- (bytevector-uint-set! bv 0 int endianness num-bytes)])
- bv))))
- ;; syntax:
- ;; SRFI-4: https://www.gnu.org/software/guile/manual/html_node/SRFI_002d4.html
- ;; BYTEVECTORS: https://www.gnu.org/software/guile/manual/html_node/Bytevectors.html
- ;; bitvector: #*1111000, (bitvector->list #*101010101010) -> (#t #f #t #f #t #f #t #f #t #f #t #f)
- ;; bytevector: #vu8(0-255 0-255 ...)
- ;; vector: #(1 2 3)
- ;; vector of hexadecimal digits -> integer: #xdeadbeef
- ;; other uniform number vectors:
- ;; https://www.gnu.org/software/guile/manual/html_node/SRFI_002d4-Overview.html
- ;; #s8(-10 1 3)
- ;; #s16(-10 1 3)
- ;; #s32(-10 1 3)
- ;; ...
- ;; equality:
- ;; (equal? #vu8(1 2 3) #u8(1 2 3))
- ;; (eqv? #vu8(1 2 3) #u8(1 2 3))
- ;; (eq? #vu8(1 2 3) #u8(1 2 3))
- ;; Big-endian means storing the most significant byte FIRST, not LAST, as the name would seem to suggest.
- ;; Little-endian means storing the least significant byte FIRST, not LAST, as the name would seem to suggest.
|