如何在 C 中存储 64 位整数?

How to store 64 digits integer in C?

我正在处理 2 个 64 位整数,需要将这两个数字相乘。 当我试图将它存储到 long long int 变量中时,出现以下编译错误:

1.c: In function ‘main’:
1.c:5:6: warning: integer constant is too large for its type.
a = 1234567890123456789012345678901234567890123456789012345678901234;

谁能告诉我如何在 C 中存储整数?

[edit] OP later 一个 64 decimal digit number.

A long long intint64_t 足以满足 64 位整数的要求。然而,最大64位整数是9,223,372,036,854,775,807,而你的数字比那个大,因此可以使用128位整数,但恐怕还是不够。

GCC 确实有一个 uint128_t/int128_t 类型,从版本 4 开始。在 Is there a 128 bit integer in gcc?

中阅读更多内容

1234567890123456789012345678901234567890123456789012345678901234 不是 64 位数字。这是一个 64 十进制数字 的数字,需要大约 210+ 二进制 位来存储。

尝试存储 64 位数字

long long s1 = 9223372036854775807;
long long s2 = -9223372036854775807 - 1;
unsigned long long u1 = 18446744073709551615u;

要在标准 C 中存储 64 位十进制数,您需要使用另一种方法,因为 C 的整数类型最多只能指定 64 个二进制数字(位),尽管更宽的 可以 存在:存储为您自己的数字数组、字符串或使用像 gmp 这样的 bignum 库。这取决于您要对存储的 64 位十进制数字执行的操作。


示例字符串方法。它缺乏缓冲区保护,也没有删除前导零并且效率不高。它确实展示了所需的流程 - basic long multiplication.

char *string_mult2(char *product, const char *a, const char *b) {
  size_t alen = strlen(a);
  size_t blen = strlen(b);
  size_t clen = alen + blen;
  memset(product, '0', clen);
  product[clen] = 0;
  for (size_t ai = alen; ai-- > 0;) {
    unsigned acc = 0;
    size_t ci = --clen;
    for (size_t bi = blen; bi-- > 0;) {
      acc += product[ci] - '0' + (a[ai] - '0') * (b[bi] - '0');
      product[ci--] = acc % 10 + '0';
      acc /= 10;
    }
    product[ci] = acc % 10 + '0';
  }
  return product;
}

int main(void) {
  char *a = "1234567890123456789012345678901234567890123456789012345678901234";
  //a = "12";
  char *b = a;
  char product[200];
  puts(string_mult2(product,a,b));
  return 0;
}

输出

在您尝试编译代码并 运行 之后,将鼠标悬停在下方以查看我的结果。

01524157875323883675049535156256668194500838287337600975522511810828928529615005335814711781866792303015211342784=27643275[]

这使用 GNU multiple precision arithmetic library

将两个 64 位十进制整数相乘

example.c

#include <gmp.h>
#include <stdio.h>

int main(void)
{
  // A 64-digit number expressed as a string
  const char str[] = "1234567890123456789012345678901234567890123456789012345678901234";

  mpz_t n;                         // mpz_t is the type defined for GMP integers
  mpz_init(n);                     // Initialize the number

  mpz_set_str(n, str, 10);         // parse the string as a base-10 number

  mpz_mul(n, n, n);                // square the number (n = n * n)

  printf("n * n = ");              // print the result
  mpz_out_str(stdout, 10, n);

  return 0;
}

使用 GMP 库编译并link

gcc -lgmp example.c -o example

输出

n * n = 15241578753238836750495351562566681945008382873376009755225118122311263526910001524158887639079520012193273126047859425087639153757049236500533455762536198787501905199875019052100

参考