-3

I know that when working with strings, from the definition the >> operator means Extract string from stream and we normally use it to store it on a variable doing something like this: std::cin >> name; With numbers it is a Bitwise right shift operator, still it seems a bit comfusing to me, why does it have 2 meanings?

I've seen examples like this:

        crc = crc16xmodem_table[((crc >> 12) ^ (*data >> 4)) & 0x0F] ^ (crc << 4);

looking at that we see crc >> 12, data >> 4.

How does this really work differently with numbers and strings? Does it have something to do how strings and ints are implemented?

Nmaster88
  • 1,197
  • 2
  • 15
  • 44

1 Answers1

3

To put it in simple mathematical terms:

x<<y == x*2^y

x>>y == x/2^y (integer division)

For example, 3 in binary is 11b. 3>>1==1 because 3/2==1, and 1==1b. Another example:

21==10101b

21>>2==5

10101b>>10b==101b

21==10101b

21<<2==84

10101b<<10b==1010100b

Nick stands with Ukraine
  • 6,365
  • 19
  • 41
  • 49
Vipin Dubey
  • 584
  • 1
  • 7
  • 23