|Baze de date
The shift operators also manipulate bits. They can be used solely with primitive, integral types. The left-shift operator (<<) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator (inserting zeroes at the lower-order bits). The signed right-shift operator (>>) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator. The signed right shift >> uses sign extension: if the value is positive, zeroes are inserted at the higher-order bits; if the value is negative, ones are inserted at the higher-order bits. Java has also added the unsigned right shift >>>, which uses zero extension: regardless of the sign, zeroes are inserted at the higher-order bits. This operator does not exist in C or C++.
If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you're operating on a long, long will be the result. Only the six low-order bits of the right-hand side will be used so you can't shift more than the number of bits in a long. There is a problem, however, with the unsigned right shift. If you use it with byte or short you might not get the correct results. (It's broken in Java 1.0 and Java 1.1.) These are promoted to int and right shifted, but the zero extension does not occur, so you get -1 in those cases. The following example can be used to test your implementation:
Shifts can be combined with the equal sign (<<= or >>= or >>>=). The lvalue is replaced by the lvalue shifted by the rvalue.
Here's an example that demonstrates the use of all the operators involving bits:
The two methods at the end, pBinInt( ) and pBinLong( ) take an int or a long, respectively, and print it out in binary format along with a descriptive string. You can ignore the implementation of these for now.
You'll note the use of System.out.print( ) instead of System.out.println( ). The print( ) method does not put out a new line, so it allows you to output a line in pieces.
As well as demonstrating the effect of all the bitwise operators for int and long, this example also shows the minimum, maximum, +1 and -1 values for int and long so you can see what they look like. Note that the high bit represents the sign: 0 means positive and 1 means negative. The output for the int portion looks like this:
The binary representation of the numbers is referred to as signed two's complement.
Politica de confidentialitate | Termeni si conditii de utilizare