Skip to content

Instantly share code, notes, and snippets.

@belmarca
Last active August 14, 2019 00:10
Show Gist options
  • Save belmarca/22c5e65932e665a281c09a389a55f227 to your computer and use it in GitHub Desktop.
Save belmarca/22c5e65932e665a281c09a389a55f227 to your computer and use it in GitHub Desktop.
(def (u8vector->uint bv (guard #t))

  (def (compute bv)
    (let ((l (fx- (u8vector-length bv) 1)))
      (let loop ((s 0) (i 0))
        (if (< i l)
          (loop (+ s (* (u8vector-ref bv i) (expt 256 (- l i)))) (+ i 1))
          (+ s (* (u8vector-ref bv i) (expt 256 (- l i))))))))

  (if guard
    (if (fx<= (u8vector-length bv) 8)
      (compute bv)
      (error "Disable guard to compute on u8vectors of length > 8." bv))
    (compute bv)))
> (u8vector->uint #u8(0 1)) 
1
> (u8vector->uint (make-u8vector 2 #xFF))
65535
> (u8vector->uint (make-u8vector 8 #xFF))
18446744073709551615
> (equal? (- (expt 2 64) 1) (u8vector->uint (make-u8vector 8 #xFF)))
#t
> (u8vector->uint (make-u8vector 10 #xFF))                          
*** ERROR IN (console)@7.1 -- Disable guard to compute on u8vectors of length > 8. #u8(255 255 255 255 255 255 255 255 255 255)
> (u8vector->uint (make-u8vector 10 #xFF) #f)    
1208925819614629174706175
> (equal? (- (expt 2 80) 1) (u8vector->uint (make-u8vector 10 #xFF) #f))
#t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment