Endian conversion problems

Dar Scott dsc at swcp.com
Tue Aug 5 22:34:02 EDT 2003


On Tuesday, August 5, 2003, at 08:51 PM, David Beck wrote:

> The question is: What is the best way to read/write a bunch of 2-byte
> integers in network byte order on Windows??

Network order is a good way to go.

> I looked in to read/writing raw chars, and then using the
> binaryEncode/binaryDecode functions to translate the raw binary data to
> numbers, but those functions require a parameter for every value that 
> gets
> encoded/decoded. I need to be able to read/write sequences of up to 
> 1120
> 2-byte integers in a reasonable amount of time, and I can neither 
> supply
> 1120 arguments to those functions, nor can I read/write the ints one 
> at a
> time, since doing this is unacceptably slow.

You can always use numToChar() and charToNum(), but I think the 
direction you are heading is probably better in this case.

Read and write your file with URL "binfile:...".

For writing, accumulate the file value with 'put ... after...' and then 
put the file.  That is fast.  Create your two byte strings one at a 
time with binaryEncode() in a loop and append them.

For reading files, you can use "repeat with i = 1 to the length of 
myBinFile by 2".  The use i to pick off a two char string and 
binaryDecode() that.  (I'm not sure I have that last cycle of that loop 
right.)

I don't think that is as slow as it looks.  (Even so, I have suggested 
an accumulation syntax for the format strings to handle data like this; 
we'll see if that goes anywhere.)


> ps. As a side note, I noticed that there is no support for 4-byte 
> integers
> in network byte order from the binaryEncode/binaryDecode functions. 
> This
> isn't a problem for me, since almost all of the data I need to 
> read/write is
> 2-byte integers, but I thought it was strange since there is support 
> for
> 4-byte integers in host byte order from the same functions.

I think this Transcript Dictionary format description is in error:

> N: convert next amount 4-byte chunks of data to unsigned integers in 
> network byte order

This is actually signed.  (I think it might accept an unsigned number 
in the high range in binaryEncode(), though.)

Dar Scott







More information about the use-livecode mailing list