Implement conversions between integers and bytevectors.
authorChris Hanson <org/chris-hanson/cph>
Fri, 28 Apr 2017 04:48:09 +0000 (21:48 -0700)
committerChris Hanson <org/chris-hanson/cph>
Fri, 28 Apr 2017 04:48:09 +0000 (21:48 -0700)
src/runtime/bytevector.scm
src/runtime/runtime.pkg

index 95c310b246076b372e2f00363514681448f3f1ae..422f5ae3fcd21c8be0d5f11a8b2f958312e86bf2 100644 (file)
@@ -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
index ac938e528a03cd514adc629609e144707dd14d08..342dea51e76762b1ef530059966afbcf8b2f6843 100644 (file)
@@ -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