Reputation: 61
I want to shift left only one bit in a specific place leaving its position 0
, so I do not want to shift the whole variable with <<
operator, here is an example: say the variable has the value 1100 1010
and I want to shift the fourth bit then the result should be 1101 0010
.
Upvotes: 2
Views: 3500
Reputation: 5040
A simpler way is
(x & 0b11101111) + (x & 0b00001000)
that is, clear the bit that will be shifted into and add the bit to be shifted, which will overflow to the left if it is 1.
Upvotes: 1
Reputation: 181068
For C++, I'd just use a std::bitset
. Since you set the bit of pos + 1
to the value of the bit at pos
, and then set the bit at pos
to 0
this translate into bitset
code that is quite easy to read. That would give you a function like
unsigned char shift_bit_bitset(unsigned char val, unsigned pos)
{
std::bitset<8> new_val(val);
new_val[pos + 1] = new_val[pos];
new_val[pos] = 0;
return new_val.to_ulong();
}
Upvotes: 4
Reputation: 15456
Maybe not the shortest/cleanest way, but this'll do it:
unsigned shift_bit = 4;
unsigned char val = 0xCA; // 1100 1010
unsigned char bit_val = val & (1 << shift_bit - 1); // Get current bit value
val = val & ~(1 << shift_bit - 1); // Clear initial bit location
val = bit_val ? // Update next bit to 0 or 1
val | (1 << shift_bit) :
val & ~(1 << shift_bit);
See it work with the test cases specified in your question and comments here: ideone
Upvotes: 2
Reputation: 206747
Steps to get there.
// Assuming C++14 or later to be able to use the binary literal integers
int a = 0b11001010;
int t = a & 0b00001000; // Pull out the 4-th bit.
t <<= 1; // Left shift the 4-th bit.
a = a & 0b11100111; // Clear the 4-th and the 5-th bit
a |= t; // Merge the left-shifted 4-th bit.
Upvotes: 7