我曾尝试使用C制作一个正的二进制到十进制数转换器,但是当我尝试输入高于1110011010110001010111(十进制3779671)的值时,程序总是返回该确切数字。我目前的作业要求它可处理的二进制数最大为111111111111111111111111111111(1073741823)。
到目前为止,我已经尝试将变量类型更改为任何其他更大的尺寸,但是似乎不起作用。这是当前代码:
#include <math.h>
void main()
{
unsigned long long int bi, de = 0;
unsigned long long int x = 0, bases;
scanf("%llu", &bi);
for(x=0 ; bi>0 ; x++, bi=bi/10){
bases = bi % 10;
de = de + bases * pow(2,x);
}
printf("%llu", de); // imprime o correspondente em decimal
}
感谢您的事先帮助。
您无法读取二进制数111111111111111111111111111111111,并将其放入无符号长整型整数中,因为无符号长整型int的限制为18446744073709551615,因此您需要将二进制数读取为字符串,然后转换每个字符改为数字:
#include <stdio.h>
#include <string.h>
#include <math.h>
unsigned long long int bin2dec(const char *string, const size_t size)
{
unsigned long long int bit, value = 0;
for(size_t index=0;index<size;index++)
{
// moving from the end to the beginning, get a character from the string
// and convert it from a character containing a digit to a number
bit = string[size-index-1]-'0';
// in the original question this was: value += bit*pow(2,index);
// but we can just do this and get the same effect
// without multiplication or library function
value += bit<<index;
}
return value;
}
int main()
{
const char * binary = "111111111111111111111111111111";
unsigned long long int decimal = bin2dec(binary, strlen(binary));
printf("%llu\n",decimal);
return 0;
}