简体   繁体   English

设置uchar的位

[英]setting bits of a uchar

I am trying to set a uchar as follows: 我试图设置一个uchar如下:

uchar num = 0;
    //0
    num <<= 1;
    //1
    num |=1;
    num <<=1;
    //0
    num <<=1;
    //1
    num |=1;
    num <<=1;
    //0
    num <<=1;
    //1
    num |=1;
    num <<=1;
    //0
    num <<= 1;
    //0
    num <<=1;
    //should be 01010100 = 84
    std::cout << " num is " << num << " int " << (unsigned int) num << std::endl;

Which should end up with the binary 8-bit sequence 01010100 which is 84 in decimal. 哪个应该以二进制8位序列01010100结尾,其中十进制为84。 However, when I print the output I get is num is ® int 168 但是,当我打印输出时,我得到的是num is ® int 168

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

The last shift is too much. 最后的转变太多了。 It multiplies 84 by 2 which gives 168 它将84乘以2得到168

You're shifting for a zero once too often at the end of your series: 在系列结束时,你经常会转为零:

//1
num |=1;
num <<=1;
//0
num <<= 1;
//0
num <<=1;

This won't generate a binary 100 but rather 1000 thus your end-value will be 这不会生成二进制100而是生成1000因此您的结束值将是

1010 1000 (168)

instead of 代替

1010 100 (84)

Remove one of those last 0 shifts and you'll be good to go: Example 删除最后0班中的一个,你会很高兴: 示例

When you want to "append" a 1 , you should first shift, then OR the 1 . 当你想“追加”一个1 ,你应该先移动,然后移动1 Otherwise you shift the just-appended 1 which becomes a 2 , hence your result is exactly twice the number you expected. 否则,你移动刚刚附加的1变为2 ,因此你的结果正好是你预期的数字的两倍。

//1
num <<= 1;
num |= 1;

//0
num <<= 1;

Then, your last shift is correct (in contrast to the other answers, which are also correct but if you simply remove the last shift your code comments are wrong). 然后,你的最后一次转换是正确的 (与其他答案相反,这也是正确的,但如果你只是删除最后一个班次你的代码注释是错误的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM