gpt4 book ai didi

c - 使用 stdint.h 和 ANSI printf?

转载 作者:行者123 更新时间:2023-12-04 00:48:35 25 4
gpt4 key购买 nike

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

我将使用一些 C99 功能,但尽量符合 ANSI C。

目前我的 bignum 库中有以下内容:

#include <stdint.h>

#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 一起使用。如果 int 是 32 位而 long 是 64 位,那将是理想的,但我不知道如何使用预处理器来保证这一点,并且当需要使用诸如 printf 之类的完全依赖于标准类型的函数时,我不再知道该怎么做使用。

最佳答案

您可以使用 <inttypes.h> 中的宏帮忙:

#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 就是这样做的。

关于c - 使用 stdint.h 和 ANSI printf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com