[REBOL] Re: Bitwise operations
From: krobillard:cox at: 14-Aug-2003 15:50
On Thursday 14 August 2003 02:22 pm, you wrote:
> Paul wrote:
> > I think REBOL needs more native functions for handling bitwise
>
> operations.
>
> Does Rebol really need it? Wouldn't it be better to use Assembler, C or
> C++ for that kind of job? Bit-twiddling usually means that one is
> interfacing with hardware, and it's usually best to use a language
> that's closer to the "metal" as it were and one that's very, very fast.
> Just my opinion.
I would welcome more natives to handle binary data. Many of my REBOL projects
involve binary data files. One such program is a binary data dissector which
takes a specification for structures in a data stream and dumps a text report
of the stream. Another is a byte-code compiler which converts a REBOL
dialect into a binary stream of instructions. In my experience dealing with
binary data is a basic part of programming.
I wish REBOL would provide a formal way to convert 32 & 64 bit IEEE
floating-point values in binary data to/from number values. Using 'third
make struct! [a [float]] [3.53]' just isn't elegant (not to mention slow),
and is not portable between all versions of REBOL.
Here are some functions I use which would be much faster as natives:
; Converts integer to 16 bit big-endian binary value.
bin16: func [n] [
to-binary reduce [ to-integer n / 256 n and 255 ]
]
bin16-le: func [n] [
to-binary reduce [ n and 255 to-integer n / 256 ]
]
; Converts integer to 32 bit big-endian binary value.
bin32: func [n] [
load join "#{" [form to-hex n "}"]
]
bin32-le: func [n /local data a b c d] [
data: form to-hex n
a: copy/part data 2
b: copy/part skip data 2 2
c: copy/part skip data 4 2
d: copy/part skip data 6 2
load join "#{" [d c b a "}"]
]
swap16: func [data] [ data/1 + (data/2 * 256) ]
swap32: func [data] [ data/1 + (data/2 * 256) + (data/3 * 65536) +
(data/4 * 16777216) ]
-Karl Robillard