JAVA (SHIFT OPERATOR)

Hi,
I really want to know SHIFT operator in Java like >> , << , >>>
Could anybody kindly help to explain??
And
byte a =-1;
a = (byte)(a>>>2);
why the output become -1??
thanks.

umm i did get them mixed up. preserved sign bit right shift is >>, pulling-zeros is >>>. so keep that in mind. (ie, 18>>2 == 10010>>2 == 11100 which is -4)
To calculate the resulting number from >>> right shifts, check this: http://www.janeg.ca/scjp/oper/shift.html
In response to your original question, it seems it's far more complicated than I at first thought. The -1 that you're getting is an odd (and rather interesting, imo) byproduct of modular arithmetic. what you wrote is exactly similar to this code (ie, my code mimics the castings that happen in your code):
        byte a = -1;
        int b = (int) a;
        int c = b>>>2;
        byte d = (byte) c;
        System.out.print(d);So what happens is A, which is a string of ones (ie 11111111) is casted to an int, B. In general, casting a byte to an int returns an int with exactly the same bits at the end with the sign bit repeated 24 times at the start (ie, 01101011-->(int)0000...00001101011). So B is 11111111111111...1111 (32 ones). Then we right shift B by 2 (we'd get the same answer right shifting it by 0, 1, 2, etc, all the way up to (and including) 24). Then we recast the int C to a byte. This is where the interesting thing happens: Depending how much we right shifted B to get C, C will be a certain number of zeros (call this Z) followed by (32-Z) ones. Apparently, in (mod 2^8) in two's complement all of these numbers are congruent to -1, so the cast gives negative one.
(remember that the int 127 cast to byte is 127, while the int 128 cast to byte is -128. conversions to a lower-bit type always happen mod 2^N, where N is the number of bits in the type we're casting to.)
BTW, thanks for this problem. i had a fun half hour figuring it out. hopefully it made some sense to you...
(EDIT: Flounder is right--you can just view the cast from int to byte as keeping the last 8 bits. much easier to think of it that way, though my definition does give some intuitions about WHY all this works.)
Edited by: a_weasel on Oct 13, 2008 8:00 PM

Similar Messages

  • Logical right shift ( ) operator

    Hi,
    I suspect a bug in the logical right shift operator >>> (as opposed to the arithmetic right shift >>).
    The documentation says "0-s will be shifted from the left". It is not the case.
    byte b = -128;                         // this means 0x80 in hex notation
    byte b1 = (byte)(b >>> 4);I would expect b1 = 0x8 (0-s shifted in from the left) but the result is
    b1 = 0xF8 instead, as if I had used the >> operator. The sign bit was shifted in from the left instead of 0-s.
    Of course, there is a workaround:
    byte b1 = (byte)((b >>> 4) & 0x0F); which is the same operation as using >>
    If this is the case, what is the purpose of using >>> instead of >> ?
    Anyway, the ONLY thing that frustrates me in the Java language that it does not support unsigned integers. It would be important for embedded systems where unsigned numbers are used more frequently.
    Any suggestions?
    Thank you,
    Frank

    sabre150:
    It depends on the size of processor you use. The Java program runs on a 32- or 64-bit processor, so there is no problem promoting from byte to short or int. But I am talking to an 8-bit processor over a network. So I get a byte stream that has to be converted to numbers here on the Java side. The data types are various: byte or short, even sometimes two 4-bit nibbles (here comes the >>> operator), signed or unsigned. If I get a two-byte sequence, I have to convert it to a short, signed or unsigned. That means in Java promoting the byte to int, shift left the high byte, OR the low byte then cast it back to short if signed, or mask with 0xFFFF if unsigned. The resulting int can be converted to string in the usual way. With distinguished signed and unsigned types, this would be done by the compiler. But I come from the Assembler (and then Pascal/Delphi) world, so it is not a big problem for me.
    I agree that this feature is used very rarely, I already wrote the conversion routines, so why bother? As a newcomer to Java (after struggling with C for years, I love it), I just wanted to see whether other people have a better and more efficient idea.
    Thank you all for your replies!
    Frank

  • Left-shift operator used on byte values

    Hello,
    I'm reviewing some problems, and I need some help. I have a program that has some code like the following:
    byte y = 10; // 00001010 in binary
    byte result = (byte) (y << 1);
    System.out.println("result: " + result); // 20.  Ok.
    result = (byte) (y << 7);
    System.out.println("result: " + result); // 0.  Ok.
    result = (byte) (y << 8);
    System.out.println("result: " + result); // 0. Why???
    // I was expecting a shift of 0 bits because the
    // right-hand operand is equal to the number of
    // bits for the size of the result type--in this case
    // 8 bits for a byte.
    // 8 % 8 = 0 number of bits for the shift.
    result = (byte) (y << 6);
    System.out.println("result: " + result); // -128.  Ok.
    result = (byte) (y << 10);
    System.out.println("result: " + result); // 0.  Why???
    // Shouldn't it be 2 bits for the shift?
    // That is, 10 % 8 = 2.
    // I was expecting 40 as the the answer for this one.I understand that for binary operations that the operands will be promoted to at least int types before execution occurs, but I still don't see how it would make a difference for the left-shift operator. Any help and clarification on this will be appreciated. It would be helpful to see the binary representation of the the "result" variable for the ones that I'm asking about. Thanks in advance.

    result = (byte) (y << 8);
    System.out.println("result: " + result); // 0. Why???
    // I was expecting a shift of 0 bits because the
    // right-hand operand is equal to the number of
    // bits for the size of the result type--in this case
    // 8 bits for a byte.the result of (y << 8) is an int, not a byte. the byte "y" is promoted to int for the bit shift. so the int result of the bit shift is 00000000 00000000 00001010 00000000. when you cast that back to byte, the 24 leftmost bits get lopped off, and you're left with zero.
    hth,
    p

  • The Shift operator Question

    Dear sir/madam
    I having question for the shift operator.
    What different between >>> and >> ?
    I have refer to sun tutorial, it state >>> is unsign, what does it mean?
    and last is
    if integer is 13
    what anwer for 13>>8
    is it move for 8 right by position? pls told me in detail
    is it answer same with the 13>>>8 ?
    Thanks for ur solutions

    You can play with the following for a while.
    final public class BinaryViewer{
      final static char[] coeffs = new char[]{(char)0x30,(char)0x31};
    public static String toBinary(int n) {
      char[] binary = new char[32];
      for(int j=0;j<binary.length;j++) binary[j]=(char)0x30;
      int charPointer = binary.length -1;
      if(n==0) return "0";
      while (n!=0){
          binary[charPointer--] = coeffs[n&1];
          n >>>= 1;
    return new String(binary);
    public static void print(int n){
        System.out.print(BinaryViewer.toBinary(n));
        System.out.print("   ");
        System.out.println(String.valueOf(n));
    public static void main(String[] args) throws Exception{
       int n=Integer.MIN_VALUE;//Integer.parseInt(args[0]);
       int m=Integer.MAX_VALUE;//Integer.parseInt(args[1]);
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
        n=1024;
        m=-1024;
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
       n=2048;
       m=-2048;
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
    }

  • Java or operator statement and expressions

    So I tried to simplify some code this morning using the java or operator and it doesn't seem to work. It went something like this:
    if ((time < 4) || (time > 10))}
    val = aVariable}
    else val=0;
    What I end up with is zero until 4 but after 10 the val does not return to 0.
    I hope this makes sense to somebody out there. I just went back to a stack of if else statements to solve the problem.
    Thanks

    I'm not sure what the problem is (except that your curly brackets are wrong), but this opacity expression works:
    if ((time < 4) || (time > 10)){
    0
    }else{
    100
    Dan

  • Shift Operation in Prodcution order.

    How to record the shift operation in the Production order?

    Hi,
    Please try to simply your subject of posting. It is not necessary your subject and body of discussion should be same.
    Yes possible to remove under SQL management studio provided you have authorization to access.
    Thanks & Regards,
    Nagarajan

  • Pda reproducible bug with logical shift operation when y 3 for arrays

    Folks,
    I have discovered a problem and wonder if this is a wider bug or if I am doing something wrong:
    Labview PDA 8.0.1  -  running on a Dell Axim:
    I create a 2x1000 array of U32 and feed it as x into the logical shift operator.  If  y is between -3 and 3, the logical shift works properly.  If y >= 4 or <= -4, then the array is returned with all zeros.
    I have reproduced this for I32 data and smaller arrays.  Logical shift works properly for scalars.
    Has anyone else seen this?  Is this a bug?
    Thanks for any help.

    It might very well be a bug. If it works differently on the PC and on the PDA then it is almost certainly one.
    I suggest you post a simple example showing this so that people with current versions of the PDA module (i.e. not me) can test this. Maybe it was even fixed for 8.2?
    Try to take over the world!

  • How can I do Shift operation in plsql

    hello,
    i want to know whether there is any package or operator to do the shift operation in plsql.
    like (myVar<<8 in c++).

    why don't you use
    myvar := mywar * power(2,8);

  • Bitwise shift operator...

    I know this is very basic but I've never done this...
    If I have an object that is an Integer, and I want to increase it by 1, isn't this how you do it?
    Object ob=new Integer(10);
    ob=ob>>1;it tells me that >> operator cannot be applied to object, int
    So what can it be applied to..?

    Ummmm,sadly, no... :(
    I really do lack basic computer skills, I don't know
    a lot about binary and stuff... but how would you do
    what I want to do..?I asked because it's quite a weird code. Just checking.
    OK, so:
    the binary shift operator can only be applied between to ints, that is primitives, no Objects (like Integer is).
    This operator is not used to increase a number, but to shift its bits by one to the right.
    Usage:
    int i,j;
    j = 10;
    i = j >> 1;
    Integer obj = new Integer(10);
    int res = obj.intValue() >> 1;
    Integer resObj = new Integer(res);

  • JCVM are the java card operating system?

    in some articles I read teh following:
    JCVM acts like an operating system. the implementation of JCVM =java card operating system?
    in some articles I read: the Java Card Operating system are JCVM, APIs,JCRE, native Methos, and another classes.
    help me please. thanks.

    The problem can be explained this way.OS and natvie function is the lowest level of the articture,which play the role of os like Windows,JCVM
    is higher,its function is platform indepent,JCRE,or javacard Framework,is the platform for the application,Industry Add-on Classes is the interface supplied by others,for instance,the javacard is used as SIM card,the class is the Sim interface,javacard applet is the applet user developed.
    Apis play the role of package,for example,Throwable � class,it is the parent class of all the exceptions.

  • Efficiency of Java String operations

    Hi,
    for an Information Retrieval project, I need to make extensive use of String operations on a vast number of documents, and in particular involving lots of substring() operations.
    I'd like to get a feeling how efficient the substring() method of java.lang.String is implemented just to understand whether trying to optimize it would be a reasonable option (I was thinking of an algorithm for efficient string pattern matching such as the Knuth-Morris-Pratt algorithm, but if java.lang.String already applies similarly efficient algorithms I would not bother).
    Can someone help?
    J

    Thanks for your comment. Yes of course you're right, I
    mean indexOf(). If so (thanks DrClap), let me enter the discussion.
    The indexOf() implements a so called "brute force algorithm".
    The performance is O(n*m), where n is the length of the text, and
    m is the length of the pattern, but is close to n on the average.
    The KMP is O(n), so the performance gain should be hardly noticeable.
    To get a real performance gain you should look at the BM (Boyer-Moore,
    O(n/m)) algorithm or some of its descendants.
    As for java.util.regex package, as far as i understand it should be
    several times slower than indexOf(), because it reads EACH character through an interface method (as opposed to direct array access in indexOf()).
    Though it's still to be proved experimentally.

  • Shift operator in work center

    Our plant works in 3 shifts. for every shift there are total six persons working on it. 2 in each shift.
    we need to assign the name of person working on the particular machine. Where can be the assignment  of the actual person working on the workcenter be made.
    thanks and warm regards.
    Edited by: pankaj lade on May 8, 2008 12:32 PM

    Hi,
    One information required..
    Why you wanted to have the operator names to be attached to your work centers?
    You can have the Operator Names at the time of Confirmation of the Operation (This is what you wanted for Tracking purpose?)
    1. Have the Operator Name or No. in Personal Number Filed in CO11N (you need to actvate the HR Transactions)
    2. Activate a Stadard Value key with Operator and during confirmation the relevnt operator can enter their name or No. there
    3. in CO11N text field as the operator to enter their name..
    Hope this helps..
    Regards,
    Siva
    Edited by: Siva Kumar M on May 8, 2008 4:22 PM

  • Shift operation on Weekly off?

    Hi
    Gurus,
    what to do when i have  to run Production on Weekly Off during urgency ?
    We have weekly off on tuesday on this day i want to carried out production.
    Should i define / change holiday calender? or what......
    Plz guide me
    Harish

    Hi,
    Goto Workcenter where you want to perform operations,
    CR02, goto Capacities view, click on capacity header, click on intervals & shifts,  For valid period select in workdays column maintain 1- Work day( overides factory calander). then its a working day for work center, although its a factory declared holiday also.
    Regards
    Jagadeesh K

  • Can shift operator overflow?

    say i have
    int a=99;
    int b=1;
    what's going to happen if I do
    a=b<<99;

    Bit-shifting wraps... So, left-shifting a 32-bit
    number by 99 is the same thing as left-shifting it by
    99 % 32, or 3. You'll get the same result if for both
    1 << 99 and 1 << 3.No it doesn't (although the result is the same.)
    It truncates the right hand argument to a number of bits. The number of bits is defined by the type of the left hand argument.
    So when i is an int then....
    (i << 99) becomes (i << (99 % 32))
    This is constrained not only in the JLS....
    http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5121
    But also in the JVM spec....
    http://java.sun.com/docs/books/vmspec/2nd-edition/html/Instructions2.doc6.html#ishl

  • Checksum Shift operator

    I am trying to write this pseudocode
    checksum = 0
    for each character, C, in the word {
         rotate the (16 bit) checksum 1 bit to the right
         XOR the character into the most significant byte of the checksum
    The code that I have written so far, which isnt really working is;
    int csum=0;
    for(int i=0;i<c.length;i++)
         csum = csum>>1;
         csum=c[i]^(csum>>8);
    }c is an int array holding the word I want to generate the checksum from.
    Can anyone see what is wrong? TIA

    wow, thanks for the quick responses!
    Is your assignment to do this directly in your code, or are you amenable to using some methods of java.lang.Integer?I can do this using which ever method I want, it is for cracking an encrypted file.The encrypted file stores a checksum in 2 bytes (in known positions) , once my program has generated a possible password it is then checked with the checksum included in the encrypted file.
    How do I rotate? Is there an operator to do this?
    Thanks again everyone

Maybe you are looking for