Skip to content

Instantly share code, notes, and snippets.

@gokselgoktas
Last active December 24, 2015 20:39
Show Gist options
  • Save gokselgoktas/a0201f3a6465b34b4494 to your computer and use it in GitHub Desktop.
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).
#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