Skip to content

Instantly share code, notes, and snippets.

@yotam5
Created November 20, 2021 16:05
Show Gist options
  • Save yotam5/decb85c851d681446f925214c6f5a692 to your computer and use it in GitHub Desktop.
Save yotam5/decb85c851d681446f925214c6f5a692 to your computer and use it in GitHub Desktop.
reverse binary simply
#include <iostream>
#include <bitset>
//reverse binary of a number
unsigned int flipping2(unsigned int a)
{
//input: 0000010110
//output:0000001101
unsigned int f = 0x0;
unsigned int size = sizeof(a) * 8;
unsigned int l = 0;
short lastbit = 0;
while(size--){
l = ((unsigned int)(1 & a) )<< size;
if(1&a){
lastbit = size;
}
a >>= 1;
f |= l;
}
f >>= lastbit;
return f;
}
// 101
int main(void){
unsigned int n;
std::cin >> n;
unsigned int f = flipping2(n);
std::cout << std::bitset<32>(f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment