C ++ what does >> do

What does β†’ in this situation?

int n = 500;
unsigned int max = n>>4;
cout << max;

He outputs 31 .

What did he do for 500 to get a value of 31 ?

+3
source share
8 answers

The bit is shifted!

Original binary file 500:
  111110100

A shift of 4
  000011111, which is 31!

Original: 111110100
1st Shift:011111010
2nd Shift:001111101
3rd Shift:000111110
4th Shift:000011111 which equals 31.

This is equivalent to doing an integer division by 16.

500/16 = 31
500/2 ^ 4 = 31

: http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/bitshift.html ( , . , )

< 0 ( ) , ().

β†’ 0 () , (), .

Bitshifting . .

+9

500 , 4 .

x >> y x / 2^y.

, 500 / 2^4, 500 / 16. 31.

+4

500 16, .

>> - , n 4 . n 2 4 , i. . 2 ^ 4 = 16. , .

+2

500 4- , , .

500 = 111110100 ()

111110100 β†’ 4 = 11111 = 31

+2

500 [1 1111 0100]
(4 + 16 + 32 + 64 + 128 + 256)

4 , 4 , :
[1 1111]

1 + 2 + 4 + 8 + 16 = 31

Hex:

500 () - 0x1F4 (hex).
4 :
0x1F == 31 (dec).

+2

111110100 - 500 . , 11111, 31 .

+2

++ ,

#include <bitset>
#include <iostream>

int main() {
    std::bitset<16> s(500);
    for(int i = 0; i < 4; i++) {
      std::cout << s << std::endl;
      s >>= 1;
    }

    std::cout << s
              << " (dec " << s.to_ulong() << ")"
              << std::endl;
}
+1

Source: https://habr.com/ru/post/1761405/


All Articles