test.c 11 error [Warning 603] Symbol 'bin' (line 8) not initialized
test.c 14 error [Warning 534] Ignoring return value of function 'gets(char *)'
test.c 14 error [Warning 421] Caution -- function 'gets(char *)' is considered dangerous
test.c 17 error [Info 725] Expected positive indentation from line 16
test.c 19 error [Warning 534] Ignoring return value of function '_fgetc(struct {...} *)'
test.c 29 error [Info 713] Loss of precision (assignment) (unsigned int to int)
test.c 47 error [Info 818] Pointer parameter 'bin' (line 24) could be declared as pointing to const
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
It was a linter, by the way.
scanf("%s",bin);
This is just a diguised version of gets(). It suffers the same ills.
". Written by some real winner named HAMMER."
...who apparently still knows more than you.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
like the comment says this turns for instance the character '1' to a numeric value 1
vegaseat
DaniWeb's Hypocrite
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Wow, dude your code makes it very clear!
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
A slight modification for the bin2dec function. Removes the nested for loop. Reduces the overhead and removes the temporary variable 'm'.
int bin2dec(char *bin)
{
int b , k, n;
int len, sum = 0;
len = strlen(bin) - 1;
for(k = 0; k <= len; k++)
{
b = 1;
n = (bin[k] - '0'); // char to numeric value
if ((n > 1) || (n < 0))
{
puts("\n\n ERROR! BINARY has only 1 and 0!\n");
return (0);
}
b = b<<(len-k);
// sum it up
sum = sum + n * b;
//printf("%d*%d + ",n,b); // uncomment to show the way this works
}
return(sum);
}
dilip.mathews
Junior Poster in Training
89 posts since Jun 2006
Reputation Points: 16
Solved Threads: 3
A nice improvement by dilip.mathews! Thanks!
vegaseat
DaniWeb's Hypocrite
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Good for you, but shorter is not always better. There is no error trapping, or explanation/comment how it works!
vegaseat
DaniWeb's Hypocrite
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
binary 10010 is calculated as 1*16+0*8+0*4+1*2+0*1 = decimal 18
hence b = b<<(len-k) does the multiplication by 1,2,4,8,16 ...
sum = sum + n * b;
// this will explain it ...
printf("%d*%d + ",n,b);
vegaseat
DaniWeb's Hypocrite
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417