Last active
February 9, 2021 09:24
-
-
Save boazsegev/e23b9551b58a20073d16ba76373a60ed to your computer and use it in GitHub Desktop.
FizBuz in C - a bitwise based approach
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
// calls `snprintf` with the correct fizbuz result. | |
// | |
// Note: zero modulus is questionable... but we assume it's fine. | |
// | |
// A response to Kevlin Henney's talk from 2019: https://youtu.be/SFv8Wm2HdNM | |
int fizzbuzz(char *dest, unsigned long dest_len, unsigned long num) { | |
// construct bit based result for the 4 possible states of fizbuz | |
unsigned s = !(num % 3); | |
s |= (!(num % 5)) << 1; | |
// convert result to string | |
switch ((s & 3)) { | |
case 0: | |
return snprintf(dest, dest_len, "%lu", num); | |
case 1: | |
return snprintf(dest, dest_len, "fizz"); | |
case 2: | |
return snprintf(dest, dest_len, "buzz"); | |
case 3: | |
return snprintf(dest, dest_len, "fizzbuzz"); | |
} | |
} | |
// test... | |
int main(int argc, char const *argv[]) { | |
const size_t test_limit = 32; | |
for (size_t i = 1; i < test_limit; ++i) { | |
char dest[32]; | |
fizzbuzz(dest, 32, i); | |
fprintf(stderr, "%zu => %s\n", i, dest); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This C code FizzBuzz function is a response to Kevlin Henney's talk from 2019: https://youtu.be/SFv8Wm2HdNM.
This structural function tests mod(3) and mod(5) only once before mapping the result to a return statement.