This code is a purely for-fun project and it comes from this challenge at freeCodeCamp. This is simply an algorithm challenge which is usually meant for JavaScript, but I decided to perform in C. It will not be used for any production reasons. Please leave any feedback you see fit, with special attention to the loops and data types. I purposely used pointer arithmetic, while, and for loops to explore different approaches to the problems. I also left the printf about number of tokens in there if you'd like to play with it by uncommenting. Also note that I've provided 2 sample binary strings but only one is currently used by default.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char* binary_agent(char *bin_str);
char bit_string_decode(char *const str);
bool bit_string_is_valid(char *bit_string);
int main(void)
{
char str[] = "01000001 01110010 01100101 01101110 00100111 01110100 00100000 "
"01100010 01101111 01101110 01100110 01101001 01110010 01100101 "
"01110011 00100000 01100110 01110101 01101110 00100001 00111111";
char str2[] = "01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 "
"01100100 01100101 01000011 01100001 01101101 01110000 00100001";
char *result = binary_agent(str);
printf("%s\n", result);
free(result);
result = NULL;
return 0;
}
// Purpose: Return an English translated sentence of the passed binary string
// "Chars" must be space-separated
// E.G. binary_agent("01000001 01110010 01100101");
char* binary_agent(char *bin_str)
{
assert(bin_str);
size_t count;
char *token = NULL;
char *delim = " ";
count = 0;
char *ptr = bin_str;
while((ptr = strchr(ptr, ' ')) != NULL)
{
count++;
ptr++;
}
ptr = NULL;
//printf("Total number of tokens %lu\n", count);
char *output_buffer = malloc(sizeof(char)*(count+1));
assert(output_buffer);
token = strtok(bin_str,delim); // token is null-terminated
if(!token) return NULL;
output_buffer[0] = bit_string_decode(token);
size_t i;
for(i = 1; token != NULL; ++i) //convert to for loop
{
token = strtok(NULL, delim);
if(!token) break;
output_buffer[i] = bit_string_decode(token);
}
return output_buffer;
}
//Parses groups of 8 1s or 0s into a char
char bit_string_decode(char *const str)
{
assert(str && bit_string_is_valid(str));
char output = 0;
size_t i;
//String needs to be valid for sure here
for(i = 0; i < 8; ++i)
{
switch(str[i])
{
case '1':
output |= 1 << 7-i;
break;
case '0':
break;
}
}
return output;
}
bool bit_string_is_valid(char *bit_string)
{
assert(bit_string && (strlen(bit_string) == 8));
while(bit_string && *bit_string != '\0')
{
if((*bit_string != '0') && (*bit_string != '1')) return false;
bit_string++;
}
return true;
}