tomcat-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ed Korthof ...@apache.org>
Subject Re: Ajpv12InputStream.java bit op dillema
Date Fri, 02 Jun 2000 11:54:47 GMT
There was a discussion of this which I happened to read on jserv-users ...
it made me curious, so i did some tests.  I'm posting this here mostly out
of curiosity -- I'm wondering if anyone knows a better idiom in Java for
insisting that bytes be treated as unsigned.  The one I'm using is: 
(a < 0 ? (int)a+256 : (int)a) ... which is ugly.

On Thu, 1 Jun 2000, Jon Stevens wrote:

> on 6/1/2000 1:21 AM, M. Greenblatt at memag@mediaone.net wrote:
> 
> > In the readWord() method of class Ajpv12InputStream.java we have the
> > following bitwise operation:
> > 
> > return ((int)((b1 << 8) | b2)) & 0xffff;
> > 
> > Does anyone happen to know the utility of the '& 0xffff' in this?  From
> > what I can see it has no effect whatsoever on the final result.

As others said, the &0xffff this doesn't make the results any less
correct.  However, unless the read() method is (*very*) broken, it also
doesn't make them any more correct: read is required to return an integer
between 0 and 255.  If it doesn't do that, we've got worse problems ...

Here's what we currently have:

******
        int b1 = read();
        if( b1 ==-1)
            return -1;

        int b2 = read();
        if ( b2==-1)
            return -1;

        return ((int)((b1 << 8) | b2)) & 0xffff;
******

The following is slightly faster (not enough to matter -- 10s of ms for
10,000 iterations); but it doesn't seem any clearer to me:

*****
       byte bytes[] = new byte[2];

       if (read(bytes, 0, 2) != 2)
           return -1;

       int val = (bytes[0] < 0 ? (int)bytes[0] + 256 : (int)bytes[0])<<8;
       val +=    (bytes[1] < 0 ? (int)bytes[1] + 256 : (int)bytes[1]);

       return val;
*****

I wouldn't mind changing the code to make it clearer, but the difference
in efficiency isn't large enough to justify a change which make make the
code even less clear.

Anyway, this certainly isn't a big deal, I was just curious about it. ;-)

thanks --

Ed









Mime
View raw message