What does >> do in Java?

前端 未结 4 1749
夕颜
夕颜 2020-11-30 04:35

Okay, I tried looking up what >>, or shift means, but it\'s way over my head as this site explains it: http://www.janeg.ca/scjp/oper/shift.html

Wh

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 05:03

    Can I assume the kid I'm talking to knows a bit about binary? :)

    All numbers can be represented in some kind of binary, like so:

       Base 10 : Base 2
       1 : 0001
       2 : 0010
       3 : 0011
       4 : 0100
       5 : 0101
       6 : 0110
       7 : 0111
       8 : 1000
    

    ... and so on.

    The shift operators basically move all of the bits (1s or 0s) across one position. So, for example: 000111 >> 1

    shifts all the bits in 000111 right by one number to produce this:

    000011

    000111 << 1

    shifts all those bits left by one, to produce this:

    001110

    If you shift by more than one, then it just moves the bits further.

    Now, depending on what language you're using and the kind of numbers you're working with, it can be a little bit more complicated than that. For example, if you are working in a language where the "most significant bit" (the one furthest to the left in a number) represents whether the number is signed or not, then the language will have to take that into account.

    Mathematically speaking, if you take an integer (and ignore the risk of overflows, which are caused by the computer running out of space to store bits,) shift left by 1 (<< 1) is the equivalent of multiplying by 2, and shift right by 1 is the equivalent of dividing by 2. (Think a bit about what a "place value" in binary maths is worth, and that'll make sense)

提交回复
热议问题