Hello,
Following is a java snippet,
System.out.println(Integer.toBinaryString(5));
System.out.println(Integer.toBinaryString(~5));
System.out.println(~5);
The output is:
101
11111111111111111111111111111010
-6
First is the binary of 5.
Second is binary inversion of 5.
Third line displays the decimal form of ~5
How to know that inversion of 5 is decimal -6 and not decimal
4294967290(I have calculated this value using calc).
Plz help.Thanks.
As others have noted, Java's "int" type is signed and 2s-complement.
As a result, every integer n will be changed by ~ to -n-1 (that is,
negated and one subtracted).
Put the bit pattern for ~5 into the low 32 bits of a Java "long", though,
with zeros for the high 32 bits, and you would indeed get 4294967290. Same
if you bit-inverted a C "unsigned int" on a platform with ints 32 bits
wide (printf("%d",(unsigned int)~5)
or an "unsigned long" on a platform
with longs 32 bits wide.
Most of the time, Java programmers don't need to worry overly much about
the exact bit representation of integers. Even when using them in I/O,
since the default representation for all Java implementations is the same
regardless of host architecture.
The major exceptions are:
* Using large values. You may need long or even BigInteger, depending.
* Doing binary-format I/O with non-Java tools reading files, writing
files, or networking with your Java one, including reading common
binary file formats like .gif. Mostly there are existing library
routines (ex. JAI/ImageIO classes in the case of .gif) for common
file formats.
* Doing work with bytes. Java's "byte" type is, unfortunately, signed.
* Doing arithmetic with chars. Java's "char" type is UNsigned.
* Implementing compare() and compareTo(). Naive subtraction could result
in an unwanted wraparound eventually. Best is to return -1, 0, or 1 as
appropriate.
Poor: return this.intField - that.intField;
Good: if (this.intField < that.intField) return -1;
if (this.intField > that.intField) return 1;
return 0;
The "poor" version has problems if the intField values get widely enough
separated. The difference might be bigger than 2147483647 in magnitude,
and then the sign of the returned value would be exactly opposite what
is desired! The "good" version, meanwhile, makes it easy to add more
subordinate sort criteria by inserting other stuff before "return 0".
Ex. if (this.intField < that.intField) return -1;
if (this.intField > that.intField) return 1;
if (this.intField2 < that.intField2) return -1;
if (this.intField2 > that.intField2) return 1;
return 0;
sorts on intField and, for objects with equal intFields, sorts on
intField2. Real world example could be sorting on last name, but
for equal last names earlier first names come first instead of all
comparing equal for position and therefore being jumbled up.