2013-06-27 41 views
0

这里是一个C++程序我今天看到:关于右移位运算符>>在C++

for (int i = 0; i < LEVELS; ++i) 
{ 
    int pyr_rows = rows >> i;  // what is the usage of >> i here ? 
    int pyr_cols = cols >> i;  // why we what to use it in this way. 

    depths_curr_[i].create (pyr_rows, pyr_cols); 
} 

我很好奇的是运营商的使用>>点击这里。我想一个简单的程序,并键入结果:

int rows = 5; 
int cols = 3; 
for (int i=0; i<5; i++) 
{ 
    int pyr_rows = rows >> i; 
    std::cout << "current i is:" << i << std::endl;  
    std::cout << "pyr_rows is: " << pyr_rows << std::endl << std::endl; 

    int pyr_cols = cols >> i; 
    std::cout << "current i is:" << i << std::endl; 
    std::cout << "pyr_cols is: " << pyr_cols << std::endl << std::endl; 

} 

,结果是这样的:

current i is:0 
pyr_rows is: 5 

current i is:0 
pyr_cols is: 3 

current i is:1 
pyr_rows is: 2   // from now on 
         // the outputs of pyr_rows and pyr_cols are weird to me 
current i is:1 
pyr_cols is: 1   

current i is:2 
pyr_rows is: 1   

current i is:2 
pyr_cols is: 0 

current i is:3 
pyr_rows is: 0 

current i is:3 
pyr_cols is: 0 

current i is:4 
pyr_rows is: 0 

current i is:4 
pyr_cols is: 0 

为什么输出是这个样子?任何人都可以解释吗?我们为什么要这样使用它?我们喜欢做任何情况?

回答

4

它不是“提取操作符”,它是右移运算符,这正是C++开始发明疯狂的方法来重载它之前的含义。我从pyr猜测这是金字塔图像处理?这个想法是,每当i增加1时,金字塔中的行数和列数减半。那是因为我的右移基本上是一个划分(舍入)2^i。

+1

好笑的是,我们几乎完全一样的wods ...开始;) –

+0

谢谢您的建议。我改变了标题。这是一个3D图像处理程序。现在它对我更加清楚了。 –

3

如果您已经列出,>>代表right shift operator。如果你考虑写成二进制形式的整数:

01101 = 13

>> i操作会使位上方朝右移i倍。因此,当i = 2,上述将导致:

00011 = 3

这是有用的以2的幂以有效地划分整数结果结束了圆形向下,所以3 >> 1等于1,但-3 >> 1平等-2。

这是arithmetic shift,这意味着前导位得到填充,所以在移位后(负数位1)负数可以保持负值。某些语言的logical shift也有>>>运算符,它总是用零填充前导位。

1

它不是一个“提取操作符”,它是最初的按位移(右)运算符,在C之前,任何人甚至已经考虑过制作C++语言。它现在被用作输入和输出文件的操作员。

int x = 4; 
int y = 1; 

cout << (x >> y) << endl; 

将产生4右移1位,这应该显示值2