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.

Which arithmetic operations are the same on unsigned and two’s complement signed numbers?

Addition, subtraction and multiplication are the same provided: Your inputs and outputs are the same size Your behaviour on overflow is wraparound modulo 2n Division is different. Many instruction sets offer multiplication operations where the output is larger than the input, again these are different for signed and unsigned. Furthermore if you are writing your … 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