Reputation:
I have the following existing integer number:
128 = 1000.0000
And I want to shift the following integer number by 2 positions to the left ...
15 = 0000.1111
... into the existing number to bitindex 6:
MyResult
should be = 1011.1100 = 188
I've tried this, but the result is wrong. Also if I change the positionsToShift
to 2:
int existingNumber = 128;
int numberToLeftShift = 15;
int positionsToShift = 6;
int myResult = (existingNumber << positionsToShift) | numberToLeftShift;
Upvotes: 0
Views: 47
Reputation: 186688
According your explanations you want numberToLeftShift
to shift
15 << 2
anf then combine with existing integer number:
(15 << 2) | 128
Implementation
int existingNumber = 128;
int numberToLeftShift = 15;
int positionsToShift = 2; // we want shift by 2 to the left; not by 6
// numberToLeftShift and existingNumber are swapped
int myResult = (numberToLeftShift << positionsToShift) | existingNumber;
Upvotes: 3
Reputation: 25144
According to your textual description, you should use
var myResult = (numberToLeftShift << positionsToShift) | existingNumber;
Upvotes: 0