From: Chris Hanson Date: Fri, 28 Apr 2017 04:48:09 +0000 (-0700) Subject: Implement conversions between integers and bytevectors. X-Git-Tag: mit-scheme-pucked-9.2.12~14^2~125 X-Git-Url: https://birchwood-abbey.net/git?a=commitdiff_plain;h=3d355e87bd00f3beed13cb073c235122ce79e439;p=mit-scheme.git Implement conversions between integers and bytevectors. --- diff --git a/src/runtime/bytevector.scm b/src/runtime/bytevector.scm index 95c310b24..422f5ae3f 100644 --- a/src/runtime/bytevector.scm +++ b/src/runtime/bytevector.scm @@ -46,6 +46,7 @@ USA. (bytevector-u8-ref 2) (bytevector-u8-set! 3) (bytevector? 1) + (integer-length-in-bits 1) (legacy-string-allocate string-allocate 1) (legacy-string? string? 1)) @@ -435,4 +436,21 @@ USA. (builder (fix:+ (fix:lsh (hex-digit (string-ref string i)) 4) (hex-digit (string-ref string (fix:+ i 1)))))) - (builder)))) \ No newline at end of file + (builder)))) + +(define (bytevector->exact-nonnegative-integer bytes) + (let ((len (bytevector-length bytes))) + (do ((i 0 (fix:+ i 1)) + (n 0 (+ (* n #x100) (bytevector-u8-ref bytes i)))) + ((not (fix:< i len)) n)))) + +(define (exact-nonnegative-integer->bytevector n) + (guarantee exact-nonnegative-integer? n + 'exact-nonnegative-integer->bytevector) + (let* ((n-bytes (quotient (+ (integer-length-in-bits n) #xFF) #x100)) + (result (make-bytevector n-bytes))) + (do ((n n (quotient n #x100)) + (i 0 (fix:+ i 1))) + ((not (> n 0))) + (bytevector-u8-set! result i (remainder n #x100))) + result)) \ No newline at end of file diff --git a/src/runtime/runtime.pkg b/src/runtime/runtime.pkg index ac938e528..342dea51e 100644 --- a/src/runtime/runtime.pkg +++ b/src/runtime/runtime.pkg @@ -1075,6 +1075,7 @@ USA. (export () (byte? u8?) bytevector + bytevector->exact-nonnegative-integer bytevector->hexadecimal bytevector->list bytevector->vector @@ -1097,6 +1098,7 @@ USA. bytevector-u8-set! bytevector=? bytevector? + exact-nonnegative-integer->bytevector hexadecimal->bytevector list->bytevector make-bytevector