1(define (from-twocomp numbits input)
2 (let ((mask (expt 2 (- numbits 1))))
3 (+ (* -1 (bitwise-and input mask))
4 (bitwise-and input (bitwise-not mask)))))
5
6(define (bytevector->number size bv)
7 (let ((shift-proc (lambda (idx) (* idx 8))))
8 (apply bitwise-ior
9 (map (lambda (index)
10 (arithmetic-shift
11 (bytevector-u8-ref bv index)
12 (shift-proc index)))
13 (range size)))))
14
15(define (bytevector->uint bv)
16 (if (> (bytevector-length bv) 10)
17 (error "maximum length of encoded uint is 10 bytes")
18 (list->bits
19 (bytevector-fold-right
20 (lambda (x ys)
21 (let* ((lst (bits->list x))
22 (no-msb (if (msb-set? x)
23 (init lst)
24 lst)))
25 (append no-msb ys)))
26 '() bv))))
27
28(define (uint->number n)
29 (let ((x (arithmetic-shift n -1)))
30 (if (lsb-set? n)
31 (bitwise-eqv x)
32 x)))