Java Reference
In-Depth Information
indicates that it is a negative number. The 2's complement of the first 7 bits (1110110) would be 001010, which is 10 in
decimal. If you consider the actual bits, 11110110, in a byte as an unsigned integer, its value is 246 (128 + 64 + 32 + 16 +
0 + 4 + 2 + 0). The following snippet of code shows how to get the value stored in a byte as an unsigned integer:
byte b = -10;
int x = Byte.toUnsignedInt(b);
System.out.println("Signed value in byte = " + b);
System.out.println("Unsigned value in byte = " + x);
Signed value in byte = -10
Unsigned value in byte = 246
The Short class contains the same two methods as the Byte class, except they take a short as an argument and
convert it to an int and a long .
The Integer class contains the following static methods to support unsigned operations and conversions:
int compareUnsigned(int x, int y)
int divideUnsigned(int dividend, int divisor)
int parseUnsignedInt(String s)
int parseUnsignedInt(String s, int radix)
int remainderUnsigned(int dividend, int divisor)
long toUnsignedLong(int x)
String toUnsignedString(int i)
String toUnsignedString(int i, int radix)
Notice that the Integer class does not contain addUnsigned() , subtractUnsigned() , and multiplyUnsigned()
methods as the three operation are bitwise identical on two signed and two unsigned operands. The following snippet
of code shows the division operation on two int variables as if their bits represent unsigned values:
// Two negative ints
int x = -10;
int y = -2;
// Performs signed division
System.out.println("Signed x = " + x);
System.out.println("Signed y = " + y);
System.out.println("Signed x/y = " + (x/y));
// Performs unsigned division by treating x and y holding unsigned values
long ux = Integer.toUnsignedLong(x);
long uy = Integer.toUnsignedLong(y);
int uQuotient = Integer.divideUnsigned(x, y);
System.out.println("Unsigned x = " + ux);
System.out.println("Unsigned y = " + uy);
System.out.println("Unsigned x/y = " + uQuotient);
 
Search WWH ::




Custom Search