Kevin Rave
Kevin Rave

Reputation: 14426

Understanding Hex number to Decimal in two compliment - Java

I am trying to understand this answer here.

How do both these 0xf2 and 0xfffffff2 values represent -14? Can you elaborate with the conversion process?

I know what is Two's complement, though.

Upvotes: 1

Views: 2546

Answers (3)

user207421
user207421

Reputation: 310884

How do both these 0xf2 and 0xfffffff2 values represent -14?

They don't.

int a = 0xf2;
int b = 0xfffffff2;

are different values. The only case where they represent the same number is:

byte a = (byte)0xf2;
byte b = 0xfffffff2;

and that's because of sign extension when the byte is used in an integer context. Note that

byte a = 0xf2;

doesn't even compile, so it's hard to see what your question is really about.

Upvotes: 0

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

0xf2 = 11110010

The first bit is sign-bit. So sign is minus. To get actual value, take 2's compliment.

11110010 -> 1's complement -> 00001101 -> Add 1 -> 00001110 = -14

Similarly, take 0xfffff...f2. Sign bit at the beginning. Take 2's complement.

1111-1111-1111.....0010 -> 1's complement -> 00000000000...1101 -> Add 1 -> 0000...1110 -> -14

Any number of preceding 1111... wouldn't make a difference to the value of a negative signed number, just as 0000.. wouldn't for positive values.


The above calculation is for 8-bit signed 0xf2 against 32-bit signed 0xfffffff2 which are both mathematically equal.

Upvotes: 3

hyde
hyde

Reputation: 62787

In binary numbers, when using two's complement, negative values have the most significant bit set to 1. Which bit it is, that depends on how many bit number it is.

0xf2 interpreted as 8-bit signed value is -14, while 0xfffffff2 interpreted as 32-bit signed value is same -14.

32-bit 0x000000f2 would be 242, same as unsigned 8-bit 0xf2 (note: Java does not have any unsigned integer types).

Upvotes: 2

Related Questions