使用stdint.h和ANSI printf?

我正在写一个bignum库,我想使用高效的数据类型来表示数字。 特别是数字的整数,以及加法和乘法时中间表示的长(如果严格地说是整数的两倍)。

我将使用一些C99function,但试图符合ANSI C.

目前我的bignum图书馆中有以下内容:

#include  #if defined(__LP64__) || defined(__amd64) || defined(__x86_64) || defined(__amd64__) || defined(__amd64__) || defined(_LP64) typedef uint64_t u_w; typedef uint32_t u_hw; #define BIGNUM_DIGITS 2048 #define U_HW_BITS 16 #define U_W_BITS 32 #define U_HW_MAX UINT32_MAX #define U_HW_MIN UINT32_MIN #define U_W_MAX UINT64_MAX #define U_W_MIN UINT64_MIN #else typedef uint32_t u_w; typedef uint16_t u_hw; #define BIGNUM_DIGITS 4096 #define U_HW_BITS 16 #define U_W_BITS 32 #define U_HW_MAX UINT16_MAX #define U_HW_MIN UINT16_MIN #define U_W_MAX UINT32_MAX #define U_W_MIN UINT32_MIN #endif typedef struct bn { int sign; int n_digits; // #digits should exclude carry (digits = limbs) int carry; u_hw tab[BIGNUM_DIGITS]; } bn; 

由于我没有编写以十进制编写bignum的过程,我必须分析中间数组并printf每个数字的值。 但是我不知道哪个转换说明符与printf一起使用。 最好我想在终端上写入以hex编码的数字。

根本的问题是,我想要两种数据类型,一种是另一种数据类型的两倍,并且使用标准转换说明符进一步将它们与printf一起使用。 如果int是32位而long是64位,那将是理想的但是我不知道如何使用预处理器保证这一点,并且当需要使用诸如printf之类的函数时,仅依赖于标准类型我不再知道该怎么做使用。

您可以使用的宏来帮助:

 #if defined(__LP64__) || defined(__amd64) || defined(__x86_64) || defined(__amd64__) || defined(__amd64__) || defined(_LP64) typedef uint64_t u_w; typedef uint32_t u_hw; #define BIGNUM_DIGITS 2048 #define U_HW_BITS 16 #define U_W_BITS 32 #define U_HW_MAX UINT32_MAX #define U_HW_MIN UINT32_MIN #define U_W_MAX UINT64_MAX #define U_W_MIN UINT64_MIN #define PRI_U_HW PRIu32 // use for formatting a `u_hw` type #define PRI_U_W PRIu64 // use for formatting a `u_w` type #else typedef uint32_t u_w; typedef uint16_t u_hw; #define BIGNUM_DIGITS 4096 #define U_HW_BITS 16 #define U_W_BITS 32 #define U_HW_MAX UINT16_MAX #define U_HW_MIN UINT16_MIN #define U_W_MAX UINT32_MAX #define U_W_MIN UINT32_MIN #define PRI_U_HW PRIu16 // use for formatting a `u_hw` type #define PRI_U_W PRIu32 // use for formatting a `u_w` type #endif 

然后:

 printf( "some u_w variable: %" PRI_U_W "\n", u_w_var); printf( "some u_hw variable: %" PRI_U_HW "\n", u_hw_var); 

它们并不漂亮,但它们就是C99的表现方式。

ANSI C不保证intlong的大小,我不认为long long是ANSI类型。 如果您不愿意或无法使用C99,唯一安全,可移植的解决方案是编写一个配置脚本,该脚本将创建使用sizeof C程序来查找具有您需要的属性的一对整数类型。 然后,您可以在该脚本中生成包括printf格式宏的宏。

你没有使用C99的原因也可能是你在没有C99编译器的情况下移植到一些古怪的平台上。 在这种情况下,你可以找出什么有效,在标题中拍打它,而不用担心可移植性。

C99并不漂亮,但确实解决了一些令人讨厌的C问题。