# convert unsigned integer to signed integer in java?

• 05-16-2010, 11:41 AM
diskhub
convert unsigned integer to signed integer in java?
is there a way to convert unsigned integer to signed integer in java?
• 05-16-2010, 11:57 AM
JosAH
Quote:

Originally Posted by diskhub
is there a way to convert unsigned integer to signed integer in java?

Java doesn't have unsigned integers; the only unsigned quantity is the char type. What do you need it for?

kind regards,

Jos
• 05-16-2010, 12:28 PM
diskhub
i wish to do the following.
i managed to do some computation to get to the following hexi
0x8765 ==> 1000 0111 0110 0101

but i wish to convert it to
0xFFFF8765 ==> 1111 1111 1111 1111 1000 0111 0110 0101

but if it is
0x4321 ==> 0100 0011 0010 0001

i wish to produce the same
0x4321 ==> 0000 0000 0000 0000 0100 0011 0010 0001

How can i do it without much steps...
• 05-16-2010, 12:59 PM
JosAH
Quote:

Originally Posted by diskhub
i wish to do the following.
i managed to do some computation to get to the following hexi
0x8765 ==> 1000 0111 0110 0101

but i wish to convert it to
0xFFFF8765 ==> 1111 1111 1111 1111 1000 0111 0110 0101

but if it is
0x4321 ==> 0100 0011 0010 0001

i wish to produce the same
0x4321 ==> 0000 0000 0000 0000 0100 0011 0010 0001

How can i do it without much steps...

You can use shorts for that purpose; shorts are also signed and sign extension (that is what you want) is built in. Parse your shorts as if they were ints and cast them to a short afterwards.

kind regards,

Jos
• 05-16-2010, 01:29 PM
diskhub
thanks. it works
short is 16 bits?
can u guide me on how by converting to short will make this work?
• 05-16-2010, 05:50 PM
JosAH
Quote:

Originally Posted by diskhub
thanks. it works
short is 16 bits?
can u guide me on how by converting to short will make this work?

Yep, a short has 16 bits. Converting it to an int uses sign extension when applicable; have a look:

Code:

```int source= 0x4123; short ssource= (short)source; int target= ssource; // == 0x00004123 int source= 0x8123; short ssource= (short)source; int target= ssource; // == 0xffff8123```
kind regards,

Jos
• 05-17-2010, 12:50 AM
diskhub
it is surprisingly that short will pick up the 16th binary and convert the front bits according to whether it is 1 or 0...

Does this apply to all other datatype?

And what if it's vice versa, when it's 16bit changing to 32?
it will also see the 16th bit and change accordingly?