Your code seems somehow baffled around a function call of strcmp()
, which isn't needed and would consistently return non-zero for any comparison between the string literal "1"
and any "sub-string" pointed to in your code (&bin[0]
, &bin[1]
), except for the one-printable-member-string &bin[2]
, if also "1"
. Let's have a walk-through.
As you have properly written in your function prototype, the pointer to the first element of the character array is being passed by value to your called function and copied as its argument. This is the "mechanism" for the part of memory populated by the array pointed to, to become visible by the called function, if its "upper bound" is known.
There are two means of having its upper bound known:
- Passing the
char
array size as additional argument to the function, or
- Null-terminating the
char
array in the calling function, so the called function can interpret it as string, which is your choice. The called function can either use strlen()
to determine string length (size), or step through it, incrementing the counter, until a null-character is reached, and read size from the counter.
If the calling function already receives the array as a null-terminated string of '0'
and '1'
characters, the second looks more practical.
Allowing for up to as many characters as allowed by the storage capacity of the return data type of the called function (in this case int
) clarifies the problem and simplifies the code. The caller function should guard against overflow.
The called function should only compare every array member's ASCII value with '1'
and convert if equal.
For this strcmp
isn't needed.
Please see the comments in this demonstration code, based on your post:
#include <stdio.h>
#include <string.h>
#define BPB 8 //bits per byte
int bin_to_dec(char *bin) //called function
{
int result=0;
int l = (int)strlen(bin);
for (int i = 0; i < l; i++){
printf("c%d: %c\n", i, bin[i]);
if(bin[i] == '1') //compare value of the i-th element
result += 1<<(l - i - 1); //convert to power-of-two and add to the result
}
return result;
}
int main(int argc, char *argv[]) //calling function
{
size_t siz = BPB*sizeof (int); //size for each char to represent one bit
char s[siz + 1]; //characters, each representing one bit + terminating '\0'
if((argc < 2)||(argc > 2)) //fail-safe check for correct count of arguments
return 1;
size_t len = strlen(argv[1]) ; //get length of the input string
if ( len > siz ) //check against too long input which would cause overflow
return 2;
strncpy(s, argv[1], len);
s[len] = '\0'; //appending the terminating null-character
for(int i = 0; i < (int)len; i++)
if((s[i] < '0')||(s[i] > '1')) //fool-proof check against 'off-limit' input
return 3;
printf("decimal: %d\n", bin_to_dec(s));
return 0;
}