Skip to content

Instantly share code, notes, and snippets.

@h2rashee
Last active August 29, 2015 14:07
Show Gist options
  • Save h2rashee/27b2c57cc5bf6bf503e0 to your computer and use it in GitHub Desktop.
Save h2rashee/27b2c57cc5bf6bf503e0 to your computer and use it in GitHub Desktop.
Elegant Re-arrangement of a Number's Bit Positions
// Pseudo code
// See original problem at https://gist.github.com/h2rashee/3b93f99ee78d16804740
// Proposed by Mike Li
int order[] = [7,6,5,4,3,2,1,0];
long x = 85;
int main() {
long y = 0;
for (int i = 0; i < order.length(); i++) {
int pos = order[i]; // look up which bit of x we want
int bit = (x >> pos) & 1; // get the pos'th bit of x
y = (y << 1) + bit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment