[英]Converting binary string to int in C
我正在用C语言将二进制字符串转换为int。我编写了一个代码,并进行了编译,但它没有按照我想要的去做,即将16位二进制字符串转换为int。 这是我的代码:
#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;
}
运行它时,它要求我输入16位二进制值。 如果我输入“ 0000000000000010”,它将显示“二进制@@是整数2007885296”而不是2。我在做什么错?
我正在通过PuTTY.exe在Linux服务器上编译并运行此代码,并且正在vi中编辑此代码,不确定是否有任何区别。
谢谢您的帮助!
您忘记了初始化result
,也不需要变量a
result=0;
for(count=0,len=strlen(input); count<len; count++)
{
result<<=1;
if(input[count] == '1')
{
result += 1;
}
}
以下代码可以干净地编译,正常工作,但不验证用户输入仅为0和1。
#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;
}
这是该代码的示例运行:
Enter a 16-bit binary value to return its integer value
101
The binary 101 is integer 5
和
Enter a 16-bit binary value to return its integer value
11000
The binary 11000 is integer 24
输入没有空终止符。 您是从键盘上读取的,但没有在结尾处添加null。
puts("Enter a 16-bit binary value to return its integer value");
while((c = getchar()) != '\n') {
input[i++];
}
input[i] = 0; // Add this.
并输入[17],所以你有一个空的地方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.