You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@tomcat.apache.org by Joe Tomcat <to...@mobile.mp> on 2002/06/19 03:20:31 UTC

Signed vs. unsigned ints in Java

I hope I will be forgiven if this is more of a java question than a Tomcat 
question:

I need to write some code that forms headers for a protocol.  This protocol 
requires specifying certain values as 16 bit unsigned ints, or even 14 bit 
unsigned values.  All the int types in java are signed.  Is there a way that 
I can take a regular 32 bit java int and come up with the string of 16 or 14 
or 4 (depending on which header field) bits that represent that value in an 
unsigned way?

Thanks for help on this.  Java certainly doesn't have the great bit handling 
abilities of C so I'm having a hard time figuring out how to put these binary 
headers together.  But Java is so awesome in every other way compared to C 
that there's no question in my mind about which one to use for pretty much 
any network service.

Thanks!

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: Signed vs. unsigned ints in Java

Posted by Denis Haskin <De...@HaskinFerguson.net>.
(Perhaps we should take this offline since it's not Tomcat-specific.)

Although Java will always give you back the signed representation of a
byte/int/whatever, you can actually set the unsigned values you want by using
casting to avoid the "loss of precision" error.

E.g. if I say:
    byte b = (byte)0xFF;
or
    byte b = (byte)256;
then all 8 bits in the byte get set (and of course if I print it out Java says
the value is -1.

Then it's simple matter of bit masking and shifting to select the bits you want
and put them in the right place in your protocol header.

I assume you don't really want a *String* of bits, right?  That threw Yoav off
<grin>.

dwh



> Joe Tomcat wrote:
>
> I need to write some code that forms headers for a protocol.  This protocol
> requires specifying certain values as 16 bit unsigned ints, or even 14 bit
> unsigned values.  All the int types in java are signed.  Is there a way that
> I can take a regular 32 bit java int and come up with the string of 16 or 14
> or 4 (depending on which header field) bits that represent that value in an
> unsigned way?


--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>