2’s complement hex number to decimal in java

This seems to trick java into converting the number without forcing a positive result: Integer.valueOf(“FFFF”,16).shortValue(); // evaluates to -1 (short) Of course this sort of thing only works for 8, 16, 32, and 64-bit 2’s complement: Short.valueOf(“FF”,16).byteValue(); // -1 (byte) Integer.valueOf(“FFFF”,16).shortValue(); // -1 (short) Long.valueOf(“FFFFFFFF”,16).intValue(); // -1 (int) new BigInteger(“FFFFFFFFFFFFFFFF”,16).longValue(); // -1 (long) Example here.

Why does the most negative int value cause an error about ambiguous function overloads?

This is a very subtle error. What you are seeing is a consequence of there being no negative integer literals in C++. If we look at [lex.icon] we get that a integer-literal, integer-literal         decimal-literal integer-suffixopt         […] can be a decimal-literal, decimal-literal:         nonzero-digit         decimal-literal ’ opt digit where digit is [0-9] and nonzero-digit is [1-9] and … Read more

Java: right shift on negative number

Because in Java there are no unsigned datatypes, there are two types of right shifts: arithmetic shift >> and logical shift >>>. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html Arithmetic shift >> will keep the sign bit. Unsigned shift >>> will not keep the sign bit (thus filling 0s). (images from Wikipedia) By the way, both arithmetic left shift and logical … Read more

Representation of negative numbers in C?

ISO C (C99 section 6.2.6.2/2 in this case but it carries forward to later iterations of the standard(a)) states that an implementation must choose one of three different representations for integral data types, two’s complement, ones’ complement or sign/magnitude (although it’s incredibly likely that the two’s complement implementations far outweigh the others). In all those … Read more

Why prefer two’s complement over sign-and-magnitude for signed numbers?

It’s done so that addition doesn’t need to have any special logic for dealing with negative numbers. Check out the article on Wikipedia. Say you have two numbers, 2 and -1. In your “intuitive” way of representing numbers, they would be 0010 and 1001, respectively (I’m sticking to 4 bits for size). In the two’s … Read more