chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] u8vector to numbers bignum


From: Peter Bex
Subject: Re: [Chicken-users] u8vector to numbers bignum
Date: Fri, 29 May 2015 08:37:25 +0200
User-agent: Mutt/1.5.21 (2010-09-15)

On Thu, May 28, 2015 at 08:18:14PM -0700, chi wrote:
> Also, a number->u8vector function would be nice. Converting a number to a hex
> string, then taking every 2 characters of that and converting that back to a
> number, for each element of the u8vector, just to keep me from accessing the
> number's bytes directly, just strikes me as terribly roundabout.
> 
> (define (number->u8vector num)
>   (let ((s (number->string num #x10)))
>     (let ((v (make-u8vector (/ (string-length s) 2))))
>       (let loop ((s s) (i 0))
>         (when (< i (u8vector-length v))
>           (u8vector-set! v i (string->number (substring s 0 2) #x10))
>           (loop (substring s 2) (+ i 1))))
>       v)))
> 
> vs
> 
> (define (numbers->u8vector num)
>   (blob->u8vector (somehow-cast-to-blob (subvector (somehow-cast-to-vector 
> num)
> 1))))

Here you go.  It's nasty, low-level and prone to break if ever the
representation is going to change (which it did a few times, so it only
works with the latest release of the numbers egg).

(define (bignum->u8vector/host-byte-order num)
  (unless (bignum? num) (error "Argument is not a bignum!" num))

  (let* ((word-size (cond-expand (64bit 8) (else 4))) ; Is there a better way?
         (bignum-contents (##sys#slot num 1))   ; Digits preceded by sign word
         (bignum-digits (substring bignum-contents word-size)))
    (blob->u8vector/shared (string->blob bignum-digits))))

The result data will be in "little endian" order of the words (least
significant bignum digit first), but the bytes within the word will be
in the host endian order.

This means the order is the REVERSE of the "slow" procedure you quoted
above.  Plus, it will include spurious zero octets (because it serializes
whole machine words):

#;6> (bignum->u8vector/host-byte-order #xff0000000000000000aa)
#u8(170 0 0 0 0 0 0 0 0 255 0 0 0 0 0 0)

Cheers,
Peter

Attachment: signature.asc
Description: Digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]