-
Using Bitwise shifts
This was going to be a question, but then I figured it out, but I thought that someone else might benefit, hence this post.
The operators <<, >>, and >>> shifts the bits in primitive datatypes.
The number following the operator specifies the number of places to shift.
EG:
Code:
int num = 2; // 0000 0010
num = num << 2; // 0000 1000 == 8
The >> shifts the bits right, EXCEPT for the sign bit, the >>> operator shifts the signbit also.
-
Exactally! The >>> operator is called a
singed shift becuase it preserves the
value of the highest order bit. Heres a little
program that i whipped up. ;)
Code:
/*
class created on 03/30/01
author brandon rohlfs
the purpose of this code is to show the process of
using the shift operators.
a left shift can be calculated by multiplying the number
being shifted by 2n, where n is the number of places being shifted
*/
import java.io.*;
class ShiftSamples{
public static void main(String[] args ){
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("Welcome to the shifter program");
System.out.println();
System.out.println("Enter the number you would like shift");
String numtoshift = buff.readLine();
System.out.println("and the amount of places you would like to shift");
String placestoshift = buff.readLine();
int shiftresult = 0;
shiftresult = Integer.parseInt(numtoshift) << Integer.parseInt(placestoshift);
System.out.println(numtoshift + " shifted " + placestoshift + " places " + " equals " + shiftresult);
}catch(IOException e){};
-
Would anyone else like to ad? As you can tell i am bored. :p