[gambit-list] Questions about reading from a port and u8vector

Bradley Lucier lucier at math.purdue.edu
Sat Jun 27 00:22:43 EDT 2009


Ah, you beat me to it.  Here's my code, with a few tests.

Brad

;; Obviously, no error checking, etc.
;; You can use read-u8 to read the bytes from a port
;; and stick them into bytevector (or do something similar
;; with the bytes directly)

;; these procedures names and calling sequences taken from the  
bytevector
;; library of R6RS.  Unfortunately, IEEE 754 does not say what the
;; specific bit sequences representing the numbers are supposed to be,
;; but usually there are only two ways that machines do it.

(define (bytevector-ieee-double-native-ref bytevector k )
   ;; extracts a double (with native endianness) from bytevector,
   ;; which I take in gambit to be a u8vector, from the positions
   ;; k, k+1, ..., k+7
   (let ((aliased-vector (f64vector 0.)))
     (do ((i 0 (+ i 1)))
	((= i 8)
	 (f64vector-ref aliased-vector 0))
       (##u8vector-set! aliased-vector i (u8vector-ref bytevector (+  
k i))))))

(define (bytevector-ieee-double-native-set! bytevector k x )
   ;; inserts a double (with native endianness) into bytevector,
   ;; which I take in gambit to be a u8vector, into the positions
   ;; k, k+1, ..., k+7
   (let ((aliased-vector (f64vector x)))
     (do ((i 0 (+ i 1)))
	((= i 8))
       (u8vector-set! bytevector (+ k i) (##u8vector-ref aliased- 
vector i)))))

#|

On my powerpc Mac portable, result is

 > (load "binary.scm")
63
191
-1.
240
248
-1.5
"/Users/lucier/Desktop/binary.scm"

On my Intel box, the sign bit is on the other end (everything is  
reversed) so
you get

 > (load "binary.scm")
0
128
1.0000000000000284
0
8
1.0000000000004832


|#

(define bytevector (make-u8vector 8 0))

(bytevector-ieee-double-native-set! bytevector 0 1. )

(display (u8vector-ref bytevector 0)) (newline)

(u8vector-set! bytevector 0 (bitwise-ior 128 (u8vector-ref bytevector  
0)))

(display (u8vector-ref bytevector 0)) (newline)

(display (bytevector-ieee-double-native-ref bytevector 0))(newline)

(display (u8vector-ref bytevector 1)) (newline)

(u8vector-set! bytevector 1 (+ 8 (u8vector-ref bytevector 1)))

(display (u8vector-ref bytevector 1)) (newline)

(display (bytevector-ieee-double-native-ref bytevector 0))(newline)




More information about the Gambit-list mailing list