Skip to content

Instantly share code, notes, and snippets.

@FauxFaux
Created October 19, 2016 18:28
Show Gist options
  • Save FauxFaux/d4b5f50f58fb5f131d36ee07a869c8eb to your computer and use it in GitHub Desktop.
Save FauxFaux/d4b5f50f58fb5f131d36ee07a869c8eb to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
static const int supported_bits = 32;
static const long long max_value = 1LL * 1000 * 1000 * 1000;
// assumption: (sizeof(bit_t) * CHAR_BIT) >= supported_bits
typedef uint_fast32_t repr_t;
// assumption: 2 ** (sizeof(bit_t) * CHAR_BIT) >= supported_bits
typedef uint_fast8_t bit_t;
static repr_t mask_for(const bit_t bit) {
assert(bit <= sizeof(repr_t) * CHAR_BIT);
return ((repr_t)1) << bit;
}
static bool is_bit_set(const repr_t in, const bit_t bit) {
return mask_for(bit) == (in & mask_for(bit));
}
static repr_t rev(const repr_t in) {
repr_t result = 0;
bit_t output_bit = 0;
bool seen_first_bit = false;
bit_t input_bit = supported_bits;
do {
if (is_bit_set(in, input_bit)) {
seen_first_bit = true;
result |= mask_for(output_bit);
}
if (seen_first_bit) {
++output_bit;
}
} while (input_bit --> 0);
return result;
}
int main() {
for (;;) {
char *buf = NULL;
size_t read = 0;
ssize_t ret = getline(&buf, &read, stdin);
if (-1 == ret) {
free(buf);
return 0;
}
char *endptr = buf + ret;
long long val = strtoll(buf, &endptr, 10);
free(buf);
if (val < 1 || val > max_value) {
// strtoll returns LLONG_MIN and LLONG_MAX for range errors, which we already catch
fprintf(stderr, "value is out of range: %lld\n", val);
return 1;
}
repr_t computed = rev((repr_t) val);
printf("%ld\n", computed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment