移位操作 [英] Shift operations

查看:97
本文介绍了移位操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到下面张贴的老乡stackoverflower之一,它像是dumbfounds我。

I saw the following posted by one of the fellow stackoverflower and it sort of dumbfounds me.

会有人在下面code片段解释移位操作:

Would someone explain the shifting operations in the following code snippet:

std::vector<bool> a;
a.push_back(true);
a.push_back(false);
//...
for (auto it = a.begin(); it != a.end();) // see 0x for meaning of auto
{
    unsigned b = 0;
    for (int i = 0; i < 8*sizeof(b); ++i)
    {
        b |= (*it & 1) << (8*sizeof(b) - 1 - i);
        ++it;
    }
    // flush 'b'
}


推荐答案

8 * sizeof的(b)是可以存储在'B'(它是一个无符号整型,即典型地32或64位)的比特数

8 * sizeof(b) is the number of bits that can be stored in 'b' (which is an unsigned int, i.e. typically 32 or 64 bits).

什么是code正在做的是,它是在矢量包装布尔值'a'到'B'级成为位。

What the code is doing is that it is packing the boolean values in vector 'a' to become bits in 'b'.

*资讯科技及电讯1演算值为1,如果在*这是真的,否则为0的布尔值,则该位左移32位减1减指数'我',也就是左移从零到31位。这现在表示的第一个元素'一'将控制在'B'(左移31),第二个元素的最显著位上B(左移30)等的第二个最显著位注意,在C的移位是算术,即不论字节或比特顺序中,X;&下; 1总是X * 2。

"*it & 1" evalutes to 1 if the boolean value at *it is TRUE, otherwise 0. The bit is then shifted left 32 bits minus 1 minus the index 'i', i.e. shifted left from zero to 31 bits. This means now that the first element of 'a' will control the most significant bit on 'b' (left shift 31), the second element the second most significant bit on 'b' (left shift 30) etc. Note that in C the shifts are arithmetic, i.e. regardless of the byte or bit order, x << 1 is always x * 2.

因此​​,例如,如果你的载体具有第一和第30元素集,'B'应该由一天结束包含二进制数千万00000000 00000000 00000100

So for example, if your vector has the first and the 30th element set, 'b' should contain by the end of the day the binary number 10000000 00000000 00000000 00000100.

这篇关于移位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆