-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,405
  • 2
  • 23
  • 65
  • 1
    It's also a bit shift operator. It has multiple meanings. – Carcigenicate Jan 04 '19 at 12:31
  • In the code shown, `crc` and `*data` are numeric variables, not streams, so `>>` is the BITWISE RIGHT SHIFT operator and `<<` is the BITWISE LEFT SHIFT operator. They are not the STREAM EXTRACTION and STREAM INSERTION operators – Remy Lebeau Jan 05 '19 at 04:05

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 is tired
  • 6,860
  • 20
  • 39
  • 51
Vipin Dubey
  • 582
  • 1
  • 9
  • 26