简体   繁体   中英

Using Left Shift operator with ones at the right of the number

I'm not very familiar with bit operators and I have this use case : when we use the left shift operator << in C++ the number will be shifted and 0 will be placed at the right of number, I want to place 1 and not zero at the right. I mean if I have a number 00000000 and I make << 3 the result need to be 00000111 and not 0 !

Simple approach is to left shift 1 by the number of bits you want set and then subtract 1

(1 << n) - 1

Eg

cout << (1 << 2) - 1 << '\n'; // prints 3
cout << (1 << 3) - 1 << '\n'; // prints 7
cout << (1 << 4) - 1 << '\n'; // prints 15
cout << (1 << 5) - 1 << '\n'; // prints 31

But note this only works if n is less than the number of bits in an integer. Otherwise it's undefined behaviour.

Here's a solution that works on any number:

int one_shift(int val, int n) {
    return ~(~0 << n) | (val << n);
}

Breakdown:

  • ~0 evaluates to 0xFFFFFFFF eg all 1's
  • ~0 << n shifts 0xFFFFFFFF by N places, resulting in a number with N zeroes on the end
  • ~(~0 << n) flips all these bits, resulting in a number with only the last N bits set
  • | (val << n) | (val << n) then does a regular left shift on our original number by N places, and sets the last N bits by oring it with our other value

Also, here's a version that works on any integer type:

template<typename T>
T one_shift(T val, int n) {
    return ~(~static_cast<T>(0) << n) | (val << n);
}

Then that's not what a left shift is.

You will have to set those bits to 1 yourself.

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