Wednesday, April 17, 2019

Integer to it's binary string representation in C

My oldest son is studying mathematics and programming in college and wrote me asking for a way to convert an integer to it's binary representation in C. My C string handling is a bit rusty, but I accepted the challenge. This was the result, maybe it can be useful for someone.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const char *int_to_binary_string(int);

#define BITS_REQUIRED (sizeof(value_to_convert) * 8)

const char * int_to_binary_string(int value_to_convert) {
  char *result_string = malloc(BITS_REQUIRED + 1);

  for (int bit_counter = BITS_REQUIRED - 1; bit_counter >= 0; bit_counter--) {
    int current_bit = value_to_convert >> bit_counter;
    strcat(result_stringcurrent_bit & 1 ? "1" : "0");
  }

  return strchr(result_string, '1');
}

int main(void) {
  int value_to_convert = 55;
  printf("%i in binary is %s\n", c, int_to_binary_string(value_to_convert));
}

And the output:

{21:32}[2.5.0]~/Desktop ➭ gcc test.c
{21:39}[2.5.0]~/Desktop ➭ ./a.out   
55 in binary is 110111

Integer to it's binary string representation in C

My oldest son is studying mathematics and programming in college and wrote me asking for a way to convert an integer to it's binary repr...