forked from sgreenlee/C-Primer-Plus-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise01.c
39 lines (31 loc) · 793 Bytes
/
exercise01.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// C Primer Plus
// Chapter 15 Exercise 1:
// Write a function that converts a binary string to a numeric value. That is,
// if you have
// char * pbin = "01001001";
// you can pass pbin as an argument to the function and have the function
// return an int value of 25.
// NOTE: "01001001" in base10 is actually 73
#include <stdio.h>
int parsebinarystring(const char * string);
int main(void)
{
// test parsebinarystring()
int result;
char * binstring = "01001001";
printf("%s in base-10 is %d.\n", binstring, parsebinarystring(binstring));
return 0;
}
int parsebinarystring(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;
}