Skip to content

Instantly share code, notes, and snippets.

@mryoshio
Created September 22, 2013 08:40
Show Gist options
  • Save mryoshio/6658001 to your computer and use it in GitHub Desktop.
Save mryoshio/6658001 to your computer and use it in GitHub Desktop.
insert m into n, bit position i to j
#include <iostream>
using namespace std;
// see http://d.hatena.ne.jp/kobapan/20090208/1281901941
int strbin2i (const std::string &s) {
int out = 0;
for (int i = 0, size = s.size() ; i < size ; ++i ) {
out *= 2;
out += ((int)s[i] == 49) ? 1 : 0;
}
return out;
}
int insert(int n, int m, int i, int j) {
int left_more_j_of_n = (n & ~((1 << j) - 1));
int right_more_i_of_n = (n & ~((1 << i + 1) - 1));
return (left_more_j_of_n | right_more_i_of_n | (m << i));
}
int main() {
int n = strbin2i("10000000000");
int m = strbin2i("10011");
int ans = insert(n, m, 2, 6);
cout << ans << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment