简体   繁体   中英

setting bits of a uchar

I am trying to set a uchar as follows:

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. However, when I print the output I get is num is ® int 168

What am I doing wrong?

Thanks

The last shift is too much. It multiplies 84 by 2 which gives 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

1010 1000 (168)

instead of

1010 100 (84)

Remove one of those last 0 shifts and you'll be good to go: Example

When you want to "append" a 1 , you should first shift, then OR the 1 . Otherwise you shift the just-appended 1 which becomes a 2 , hence your result is exactly twice the number you expected.

//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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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