无符号长长溢出

时间:2016-02-11 17:33:40

标签: c++ c printf scanf

我试图理解为什么这个程序在2 ^ 20-1值之后溢出。我的所有变量都被声明为无符号long long,但当我输入1048756(即2 ^ 20)时,它会溢出,而不是以二进制数转换它。我认为u-l-l的范围是2 ^ 64-1。 我包含limits.h库,最大值为8个字节。这是代码:

$scope.functionlist = [];

输出是:     #include <stdio.h> int main(){ unsigned long long n = 100000000; printf("%llu \n",decimal_binary(n)); return 0; } unsigned long long decimal_binary(unsigned long long n) { unsigned long long rem, i=1, binary=0; while (n!=0) { rem=n%2; n/=2; binary+=rem*i; i*=10; } return binary; } (显然不是二进制数)

4 个答案:

答案 0 :(得分:5)

 18446744073709551615 // 2^64-1 
100000000000000000000 // 2^20 in your funny "decimal binary"

现在看到问题?

顺便说一句,如果您希望从中获取平台依赖性,请使用uint64_t中的stdint.h代替unsigned long long

答案 1 :(得分:3)

您真正想要的是以二进制格式输出数字。您不能将转换返回到这样的整数类型。你需要构造一个字符串:

void decimal_binary(unsigned long long n, char str[])
{
  unsigned long long rem, len=0, temp, i;
  while (n!=0)
  {
    rem=n%2;
    n/=2;
    // put the binary digit into the string
    str[len++] = rem ? '1' : '0';
  }
  str[len] = '\x0';
  // the digits were inserted in reverse order, so reverse the string.
  for (i=0;i<=len/2;i++) {
    temp = str[i];
    str[i] = str[len-1-i];
    str[len-1-i] = temp;
  }
}

int main(void){
    char buff[200];
    unsigned long long n = 100000000;
    decimal_binary(n,buff);
    printf("%s \n",buff);
    return 0;
}

输出:

101111101011110000100000000

答案 2 :(得分:0)

让你的代码检测数学变得太大。

#include <stdio.h>
#include <limits.h>

unsigned long long decimal_binary(unsigned long long n)
{
  unsigned long long rem, i=1, binary=0, n0;
  n0 = n;
  while (n!=0)
  {
    rem=n%2;
    n/=2;
    binary+=rem*i;
    if (i > ULLONG_MAX/10) {
      printf("OF %llu %llu\n", n0 , i);
      return 0;
    }
    i*=10;
  }
  return binary;
}


int main(){
  unsigned long long n = 100000000;
  printf("%llu %llu\n",n,decimal_binary(n));
  n = 100000;
  printf("%llu %llu\n",n, decimal_binary(n));
  return 0;
}

输出

OF 100000000 10000000000000000000
100000000 0 
100000 11000011010100000 

答案 3 :(得分:0)

main()
{
unsigned long long n = 100000000;
int i;
for(i=sizeof(unsigned long long int)*8-1;i>=0;printf("%llu",n>>i--&1));`
}
OUTPUT::00000000 00000000 00000000 00000000 00000101 11110101 11100001 00000000