Results 1 to 3 of 3

Thread: Using Bitwise shifts

  1. #1

    Thread Starter
    Hyperactive Member CaptainPinko's Avatar
    Join Date
    Jan 2001
    Location
    London, Ontario, Canada
    Posts
    332

    Post 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.
    "There are only two things that are infinite. The universe and human stupidity... and the universe I'm not sure about." - Einstein

    If you are programming in Java use www.NetBeans.org

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    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){};

  3. #3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width