I'm converting a binary string to an int in C. I wrote a code and it compiles but it's not doing what I want it to, which is converting a 16-bit binary string to an int. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char input[16];
int result;
char c;
int i;
i = 0;
int count = 0;
int a = 1;
puts("Enter a 16-bit binary value to return its integer value");
while((c = getchar()) != '\n') {
input[i++];
}
for(count = strlen(input) - 1; count >=0; count--)
{
if(input[count] == '1')
{
result += a;
}
a <<= 1;
}
printf("The binary %s is integer %d", input, result);
return 0;
}
When I run it, it asks me to enter a 16 bit binary value. If I enter "0000000000000010" it prints "The binary @@ is integer 2007885296" instead of 2. What am I doing wrong?
I'm compiling and running this code on a Linux server through PuTTY.exe and I'm editing this code in vi, not sure if that makes any difference.
Thanks for the help!
the following code cleanly compiles,works correctly, but performs no validation that a user input is only 0s and 1s.
#include <stdio.h>
#define BINARY_LEN (16)
int main( void )
{
char input[ BINARY_LEN+1 ] = {'\0'};
int c;
int i=0;
puts("Enter a 16-bit binary value to return its integer value\n");
// EDIT2: increase length to allow for trailing NUL byte
for( ; i<BINARY_LEN; i++)
{
if( (c = getchar()) != EOF && '\n' != c)
{
input[i] = (char)c;
}
else
{
break;
}
}
int result = 0;
for( int j=0; j<i; j++ )
{
// EDIT1: move shift statement to create proper result
result <<= 1;
if(input[j] == '1')
{
result |= 1;
}
}
printf("The binary %s is integer %d", input, result);
return 0;
}
here is an example run of the code:
Enter a 16-bit binary value to return its integer value
101
The binary 101 is integer 5
and
Enter a 16-bit binary value to return its integer value
11000
The binary 11000 is integer 24
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments