Write a function that converts a binary string to a numeric value. - C Data Type

C examples for Data Type:int

Description

Write a function that converts a binary string to a numeric value.

Demo Code

#include <stdio.h>

int convertBinaryStringToInt(const char * string);

int main(void)
{
  int result;/*from ww w . j  a  v  a 2  s.c  o m*/
  char * binstring = "01001001";
  printf("%s in base-10 is %d.\n", binstring, convertBinaryStringToInt(binstring));

  return 0;
}

int convertBinaryStringToInt(const char * string)
{
  // convert a binary string to a numeric value

  int retval = 0;
  while (*string != '\0')
  {
    retval <<= 1;
    if (*string == '1')
      retval |= 1;
    string++;
  }
  return retval;
}

Result


Related Tutorials