Last active
December 24, 2015 20:39
-
-
Save gokselgoktas/a0201f3a6465b34b4494 to your computer and use it in GitHub Desktop.
This Gist solves the problem specified at: https://www.spotify.com/fi/jobs/tech/reversed-binary/
Unlike most of its counterparts this one runs in constant-time and makes explicit use of bit-hacks and intrinsics (whenever possible).
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 <stdlib.h> | |
#include <stdio.h> | |
static inline unsigned int reverse_bits(register unsigned int number) | |
{ | |
register unsigned int shift = __builtin_clz(number); | |
number = (((number & 0xAAAAAAAA) >> 0x01) | | |
((number & 0x55555555) << 0x01)); | |
number = (((number & 0xCCCCCCCC) >> 0x02) | | |
((number & 0x33333333) << 0x02)); | |
number = (((number & 0xF0F0F0F0) >> 0x04) | | |
((number & 0x0F0F0F0F) << 0x04)); | |
return __builtin_bswap32(number) >> shift; | |
} | |
int main(int count, char *arguments[]) | |
{ | |
unsigned int number = 0; | |
scanf("%u", &number); | |
printf("%u\n", reverse_bits(number)); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment