# Thread: convert unsigned integer to signed integer in java?

1. Member
Join Date
May 2010
Posts
25
Rep Power
0

## convert unsigned integer to signed integer in java?

is there a way to convert unsigned integer to signed integer in java?

2. 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

3. Member
Join Date
May 2010
Posts
25
Rep Power
0
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...

4. 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

5. Member
Join Date
May 2010
Posts
25
Rep Power
0
thanks. it works
short is 16 bits?
can u guide me on how by converting to short will make this work?

6. 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:

Java 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

7. Member
Join Date
May 2010
Posts
25
Rep Power
0
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?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•