Created
September 22, 2013 08:40
-
-
Save mryoshio/6658001 to your computer and use it in GitHub Desktop.
insert m into n, bit position i to j
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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