[REBOL] using struct! to convert values to binary! datatype
From: rebol-list2::seznam::cz at: 16-Oct-2002 13:18
Hello rebol-list,
thanks to discussion about the system-port I just found that the struct! is free in Rebol,
so I started to play with it and found, that it's realy good for
converting values to binary! format. For example the first thing in
my %make-swf.r file - converting integer! to Unsigned 32-bit integer
value:
I was using this ugly function:
int-to-ui32: func[i [number!]][head reverse load rejoin ["#{" to-hex to-integer i "}"]]
t: now/time/precise loop 100000 [int-to-ui32 100] now/time/precise - t
;== 0:00:02.143
;With the struct! I can do:
int-to-ui32-st: func[n][third make struct! [n [integer!]] to block! n]
t: now/time/precise loop 100000 [int-to-ui32-st 100] now/time/precise - t
;== 0:00:00.6
As you can see, it's much more faster, but I'm still creating new
struct! - why not to use just one:
ui32-struct: make struct! [value [integer!]] none
int-to-ui32-st: func[i][ui32-struct/value: i copy third ui32-struct]
int-to-ui32-st 100
;== #{64000000}
t: now/time/precise loop 100000 [int-to-ui32-st 100] now/time/precise - t
;== 0:00:00.19
;Isn't it nice? It's faster!
;In the same way I can replace my old slow functions as well:
int-to-ui16: func[i [number!]][head reverse load rejoin ["#{" skip mold to-hex to integer!
i 5 "}"]]
int-to-ui8: func[i [number!]][load rejoin ["#{" skip mold to-hex to integer! i 7 "}"]]
int-to-bits: func[i [number!] bits][skip enbase/base load rejoin ["#{" to-hex to integer!
i "}"] 2 32 - bits]
;to these new one:
ui16-struct: make struct! [value [short]] none
int-to-ui16-st: func[i][ui16-struct/value: i copy third ui16-struct]
int-to-ui8-st: func[i][ui16-struct/value: i copy/part third ui16-struct 1]
int-to-bits-st: func[i [number!] bits][skip enbase/base head reverse int-to-ui32-st i
2 32 - bits]
t: now/time/precise loop 100000 [int-to-ui16 100] now/time/precise - t
;== 0:00:02.344
int-to-ui16-st 100
;== #{6400}
t: now/time/precise loop 100000 [int-to-ui16-st 100] now/time/precise - t
;== 0:00:00.201
t: now/time/precise loop 100000 [int-to-ui8 100] now/time/precise - t
;== 0:00:02.173
int-to-ui8-st 100
;== #{64}
t: now/time/precise loop 100000 [int-to-ui8-st 100] now/time/precise - t
;== 0:00:00.351
int-to-bits 100 16
;== "0000000001100100"
t: now/time/precise loop 100000 [int-to-bits 100 16] now/time/precise - t
;== 0:00:02.404
int-to-bits-st 100 16
;== "0000000001100100"
t: now/time/precise loop 100000 [int-to-bits-st 100 16] now/time/precise - t
;== 0:00:00.801
I'm really happy to see, that we are going faster and faster:-))
The %make-swf.r file should be uploaded with this improvement and you can
just download it from here:
http://oldes.multimedia.cz/swf/make-swf.r
cheers Oldes