1. bytes_to_int bug?

I recently needed to read some binary integers from a file, so
I used the routine:

   function read_16bit( handle )

      integer b1, b2

      b1 = getc( handle )
      b2 = getc( handle )

      return (b2*256) + b1

   end function

This worked fine most of the time, on most files, but in some cases
would return something like -254, which was clearly not right. This
was because it was reading two #FFFFs, which it read as -1. So I
changed the code to:

   function read_16bit( handle )

      integer b1, b2

      b1 = getc( handle )
      b2 = getc( handle )

      return bytes_to_int( { b1, b2, 0, 0 } )

   end function

But this still did not work. Finally, I changed it to:

   function read_16bit( handle )

      integer b1, b2

      b1 = getc( handle )
      b2 = getc( handle )

      return and_bits(b2*256, b1)

   end function

Which returned a reasonable result.

My question: is there a bug in bytes_to_int (and, by
implication, ints_to_byte)?

-- David

new topic     » topic index » view message » categorize

2. Re: bytes_to_int bug?

David Cuny wrote:

>   function read_16bit( handle )
>      integer b1, b2
>      b1 = getc( handle )
>      b2 = getc( handle )
>      return (b2*256) + b1
>   end function

> This worked fine most of the time, on most files, but in
> some cases would return something like -254, which was
> clearly not right. This was because it was reading
> two #FFFFs, which it read as -1.

getc() should always return a number between 0 and 255
*except* when it is at end-of-file, where it will return -1.
Are you sure that you weren't at end-of-file? I wrote
two #FF bytes to a file and read them back with your function.
It gave me 65535 (#FFFF) as it should.

> So I changed the code to:
>   function read_16bit( handle )
>      integer b1, b2
>      b1 = getc( handle )
>      b2 = getc( handle )
>      return bytes_to_int( { b1, b2, 0, 0 } )
>   end function

bytes_to_int({b1,b2,0,0}) should give the same result. It
simply multiplies b2 by 256 and adds b1.

Regards,
     Rob Craig
     Rapid Deployment Software

new topic     » goto parent     » topic index » view message » categorize

Search



Quick Links

User menu

Not signed in.

Misc Menu