From 3d355e87bd00f3beed13cb073c235122ce79e439 Mon Sep 17 00:00:00 2001 From: Chris Hanson Date: Thu, 27 Apr 2017 21:48:09 -0700 Subject: [PATCH] Implement conversions between integers and bytevectors. --- src/runtime/bytevector.scm | 20 +++++++++++++++++++- src/runtime/runtime.pkg | 2 ++ 2 files changed, 21 insertions(+), 1 deletion(-) 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 -- 2.25.1