fork download
  1. #include <iostream>
  2. #include <limits>
  3. #include <cmath>
  4. #include <bitset>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9. // your code goes here
  10. unsigned x = 0b01111100010000000000000000000010;
  11. //result shud be 10111100010000000000000000000010
  12. unsigned pattern = 0b10111;
  13. size_t numOfBitsToBeReplaced = 4;
  14.  
  15. size_t afterBitPos = floor(log2(x)) - numOfBitsToBeReplaced + 1;
  16. size_t numberOfBits = (std::numeric_limits<unsigned>::digits - floor(log2(x)) - 1 + numOfBitsToBeReplaced );
  17.  
  18. //Clear "numberOfBits" MSBs
  19. x <<= numberOfBits;
  20. x >>= numberOfBits;
  21.  
  22. pattern <<= afterBitPos; //Position them in MSB positions.
  23.  
  24. x = x | pattern;
  25.  
  26. std::bitset<32> y(x);
  27.  
  28. cout << y;
  29.  
  30. return 0;
  31. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
10111100010000000000000000000010