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

Similar Messages

  • Is signed right shift operator shows starnge working?

    can anyone explain abt this stange behaviour !!!
    int i = 1;
    pBinInt("i >>= 10 ",i);
    static void pBinInt(String s, int i) {
         System.out.println(s + ", int: " + i + ", bin: ");
         System.out.print("\t");
         for(int j = 31; j >=0; j--)
              if(((1 << j) & i) != 0)
                   System.out.print("1");
              else
                   System.out.print("0");
         System.out.println();
    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.
    unsigned right shift >>>, which uses zero extension: regardless of the
    sign, zeroes are inserted at the higher-order bits.
    but output shows :
    i >>= 10 , int: 1, bin:
    00000000000000000000000000000001
    shouldn't it be 00000000000000000000000000000000

    You print the binary representation of i, which is 1, instead of i >> 10, which is 0.

  • Signed right shift operator

    Hello,
    why -1 >> 1 get -1, and -2 >> 1 also get -1?
    How does >> operator works on negative number?
    thanks.

    it does set 1's to the input
    example if u have
    1111 1110  which is -2 the operator
    do the following
    he set a new 1 at the first position and move the rest one step to the right.
    1 111 1111 and the 0 goes out better example
    1011 1111 >> 1 =
    110111111

  • 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!

  • 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();
    }

  • Bitwise Right Shift vs Divide by 2

    Something that just pondered across my mind.
    Bitwise operators have their uses, and I've always known about right/left shifting to divide/multiply by 2. I recently did some empirical analysis on an algorithm using this technique, and I had to iterate it over a trillion times before I started seeing any timing differences, and even then they were in the order of 0.0001 milliseconds.
    Is the performance argument for using bitwise over standard divide still applicable on modern day processors? When I use any kind of algorithms doing this kind of operation, they probably won't loop more than a few million times at most. For readability/understandability I may as well stick with divide by two.
    Perhaps it is only significantly faster in certain languages (e.g. C)?
    Regards,
    Rob.

    Yes. You are correct. In modern operators you will not gain anything by using shift operators in place of division. But the point is even though division, multiplication operators are available for you as a high level programmer, in processor level those operations not available. So multiplication and division are carried out using shift operations in the processor level. In hardware level, a processor supports only a few basic operations like addition, negation, shifting. But when you are using java, you are working at a very high layer so that even complex operators are available for you.
    Shift operators and other bitwise are very handy if you are manipulation some hardware from within your java application. If you are doing serial port/parallel port programming, you will find these bitwise operators useful.

  • 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

  • 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);

  • Wireless keyboard right shift don't work with some keys but left shift works

    So, this is really a strange behaviour under Mavericks 10.9.5
    My right shift doesn't like some "keys" and some keys don't like the shifts ( either left or right ). For example:
    doing a " ? " or a " B " or a " % " with the right shift doesn't work. I mean, after i remove the batteries and stay without using the keyboard for a day or two, when i get back to it, it works for a couple of minutes. But after that... i just can do a capital B or a ? with the right ****. Although i can do all other characters.
    the " t " key is another one. No caps here, with either left or right shift key. But the key by itself is working just fine.
    So i'm not really 100% convinced it's an hardware fault, because the all keys are working properly in other situations.
    Any idea about this strange behaviour?
    thank you for your time,
    Regards
    Pedro.

    Hello Postmodum,
    Check out the article below and turn on the keyboard viewer to see what happens to the keyboard when you press the right shift key. You may find out that it may be linked to add another combination of keys, which can produce the odd behavior that you are describing. 
    One or more keys on the keyboard do not respond
    http://support.apple.com/kb/TS1381
    Regards,
    -Norm G. 

  • Spill has caused right shift key to be stuck on

    A few months ago I spilled juice on my MBP keyboard (out of warranty - purchased June 2012). I removed all the keys effected and cleaned them. The result of this was that the right shift key was stuck on and it would only start in safe mode + I couldn't log in because I could only type in caps. This is what I did:
    I plugged in a usb keyboard - was able to log in
    I downloaded keyremapper4mac and disabled the right shift key so I could type in NOT CAPS
    Switched to automatic login so I wouldn't be prompted to enter my password anymore
    Removed the usb keyboard
    Again, MBP would only start in safe mode. Then I found out that the key remapper would only work when the computer wasn't in safe mode. I did some googling and found a key combination that would stop the MBP from starting in safe mode. I have left my computer on for awhile now (not shutting it down) and yesterday I shut it down. I started it up holding down the cmd/shift and my login screen came up.
    My problem is that I think I may have forgotten the key combination to bypass the safe mode boot up and I don't know why my login screen came up - maybe because of the key combo I used temporarily turned off the automatic login.
    Does anyone know the combination of keys to press to get past the safe boot so my computer will start up normally? I am running 10.7.5.
    Thanks!!

    Someone else said to try and reboot by holding down the menu and play button on the remote for several seconds and then try again. It worked for several people and seems to be working for me now.

  • Why does my Left Shift +Num Keys produce Euro characters and Right Shift + Num Keys produce American?

    I am running Lion (10.7.4) on my 2010 13" MBP. When I press my Left Shift and various Num Keys (1-9), I get Euro characters (⁄ € ‹ › fi fl ‡ ° · ‚). When I use my Right Shift, I get the standard American characters (! @ # $ % ^ & * ( )).
    I have already tried restarting my computer, but this has not helped. In my language/keyboard settings, everything is set to USA. I do have multiple inputs on this machine but the flag is always on US. Occasionally, I switch to Japanese keyboards but those are not active and the problem described above appears when the US flag is displayed.

    It looks like your right shift is somehow also depressing the option/alt key.  I would suspect damage to your keyboard, which may need repair/replacement.

  • 3 letters + left shift key not working - 2 of them + right shift key working

    Hi all,
    as in subject, I have just bought a laptop g50-45, italian keyboard.
    I encountered this problem:
    "LEFT shift key" + "e" or "d" or "c" combinations do not work. Nothing happens.
    "RIGHT shift key" + "e" or "d" work properly
    "RIGHT shift key" + "c" do not work. Nothing happens
    CAPS key + "e" or "d" or "c" work properly.
    I noticed this issue before making any updates of  windows 8.1
    I tried making an update of the bios and later updating windows but the problem is still there.
    I check with an external keyboard and everything work correctly
    I don't think it could be a mechanical problem because "e", "d" and "c" keys alone work properly, so it seems more a software side problem.
    Thank you for your help.

    thanks, i thought there some quick procedure to do before heading to apple store. i was just wondering, it was working for a while, and then suddenly like that. i have macbook 10.6.8 software. intel core 2 duo. less than a year old, if i'm not mistaken.

  • Aluminum Keyboard keys "n", "y", and right "shift" not working

    My cat knocked over a glass of water on my desk, and while the keyboard attached to my MacBook didn't get water directly into it from the top, it was eventually surrounded in water. It's now dry, and everything works ok except for the N Y and right SHIFT keys. Has this happened to anyone else? Do you know how to fix it? I've tried in in my MacBook Pro and the same keys don't function. I've just tried taking a hairdryer to it to no avail.
    Any other suggestions? Perhaps its time to buy the wireless version afterall.
    Thanks!
    D.

    No real suggestion than to let it dry out more. If it was just water then there's a decent chance that it will "probably" work.
    You might have a look at Removing the individual keys. I wouldn't suggest actually trying to take it apart!

  • My shift-r, right shift-f, and right shift-v is not working.

    I've seen questions in the forum about shift-r not working, I've looked into my system preferences and it appears there are no short cuts associated with shift-r.  My right shift-f and right shift-v are not working either.  I'm using a new iMac (10.7.2) with the bluetooth keyboard that came with it.  If I use caps lock I can get capital R, F and V.  It's very strange.  I'm assuming it's a setting that's messed up versus a bum keyboard?  Thanks for any help you can give!

    Good deal, glad it's taken care of. I had a wireless keyboard on which the caps lock key stayed lit all the time, even though it did turn the lock on and off. And sometimes it wouldn't light at all. I took it (just the keyboard) to a local AASP and they checked it out and called to say my new keyboard was ready to be picked up.

Maybe you are looking for

  • Windows Phone and Windows 8 Mail App not sending email from Reply/Forward

    I have recently upgraded from Windows 8 to 8.1. After a successful upgrade I configured the Windows 8 Mail app to also sync with Exchange (2010 in house server). On my Windows Phone (Nokia Lumia 800) I have the same account configured. This resulted

  • Sales orders not showing on MD04

    Hi Gurus, Last week we had copied production environment into quality system. Now when the users are creating sales orders in Q system, they are not able to see the sales orders in MD04? What is the reason for this? Thanks Anusha

  • Good Receipt Indicator in PO

    Hello; I wanted to know if someone experienced something about the good receipt indicator (GRI) in the PO, when the PO line item has an account assignment the good receipt indicator in the delivery tab becomes active but if the PO line item does not

  • Cannot view pdf using Internet Explorer 8.0

    Running Vista 64-bit, IE8.0, Adobe Acrobat 9.4.1 (Pro).  I cannot view pdf documents on line --- a blank page opens, but no document is visible.  Java is loaded, ActiveX controls are in default mode, and I've done a "Repair Adobe Installation".  Anyo

  • Regarding Interaction Records Creation

    Hi All, I am implementing the BADI CRM_IC_IARECORD  and write the code in BEFORE_IR_CREATE. Here i am going to suppress the creation of interaction record if user has not pressed save button. Could you please anybody suggest me here how to get whethe