【问题标题】:gcc 7.3 128-bit unsigned integer operationgcc 7.3 128 位无符号整数运算
【发布时间】:2020-07-06 16:57:06
【问题描述】:

我对 128 位整数的使用感到困惑。 请看测试代码:

uint128_t test_data = 0x00000000FFFFFFFF0101010101010101;
uint64_t test_data_h = test_data  >> 64;
uint64_t test_data_l = test_data ;
printf("test_data 0x %016llx %016llx\n", test_data_h, test_data_l);

我希望test_data_h 为 0x00000000FFFFFFFF,但结果是:

test data 0x 0000000000000000 0101010101010101

这是为什么?

【问题讨论】:

  • 请花一分钟时间关注tour 了解这个社区的运作方式。如果一些答案对你有帮助,你应该点击绿色复选标记acceptit
  • 这能回答你的问题吗? Assigning 128 bit integer in C

标签: c gcc 128-bit int128


【解决方案1】:

许多编译器不支持 128 位常量。

相反

// uint128_t test_data = 0x00000000FFFFFFFF0101010101010101;
uint128_t test_data = (((uint128_t) 0x00000000FFFFFFFF) << 64) | 0x0101010101010101;

提示:启用所有编译器警告。

【讨论】:

【解决方案2】:

GCC 不支持 128 位整数文字

GCC 不支持为 long long 整数小于 128 位宽的目标表示 __int128 类型的整数常量。

128-bit Integers

所以你必须用更小的部分来构建它((unsigned __int128)high &lt;&lt; 64) | low


如果您打开所有警告,您会看到

<source>:6:35: warning: integer constant is too large for its type
    6 |     unsigned __int128 test_data = 0x00000000FFFFFFFF0101010101010101;
      |                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Demo on Godbolt

因为整数字面量的类型是“the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used”,并且类型列表不包含像__int128 这样的非标准类型

C99 还支持“extended integer types” 并且在同一页面中您也可以看到

如果整型常量的值太大而无法放入后缀/基数组合所允许的任何类型,并且编译器支持扩展整型类型(例如__int128),则可以给常量赋予扩展整型类型;否则,程序是非良构的。

integer constant

不幸的是__int128 is not an extended integer type in GCC。您可以很容易地看到 intmax_t 映射到 long long 而不是 __int128。因此你不能有__int128 文字,除非编译器有另一个扩展,比如ICC。你可以看到Godbolt link above中没有来自ICC的相关整数文字警告

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2016-10-11
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多