[英]Binary to decimal converter in C doesn't work after a certain number
我尝试使用 C 制作正二进制到十进制数转换器,但是当我尝试输入高于 1110011010110001010111(十进制为 3779671)的值时,程序总是返回那个确切的数字。 我当前的任务要求它处理高达 1111111111111111111111111111111 (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
}
我在这里先向您的帮助表示感谢。
你不需要所有的索引和添加。 您可以简单地从右侧移入位:
#include <stdio.h>
#include <string.h>
unsigned long long int bin2dec(const char *string)
{
unsigned long long int value = 0;
while (*string != '\0')
{
// make room for the next bit by shifting what is there already
value <<= 1;
// *string != '0' gives 1 if the current character is not '0', else 0
value |= *string != '0';
string++;
}
return value;
}
int main(void)
{
// 7 F C F F 4 F A F F F
const char * binary = "1111111110011111111010011111010111111111111";
unsigned long long int decimal = bin2dec(binary);
printf("%llX\n", decimal);
return 0;
}
您无法读取二进制数 11111111111111111111111111111 并将其放入 unsigned long long 整数中,因为 unsigned long long 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;
}
在这里试试: https : //onlinegdb.com/Skh7XKYUU
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.