c++ - 位在 size_t 中出现两次

标签 c++ bit

这可能是一个非常愚蠢的问题,所以请保持温和。如果我运行以下代码:

#include <climits>
#include <cstdint>
#include <stdio.h>

typedef uint64_t obs;

int main () {
    printf("Size : %i\n",sizeof(obs)*CHAR_BIT);

    obs value = 1 << 3;
    printf("Number: %zu\n",value);

    printf("Bits : ");
    for (size_t ind = 0; ind < sizeof(obs)*CHAR_BIT; ind++) {
        if (value & (1 << ind)) {
            printf("%zu ",ind);
        }
    }
}

对于各种 typedef,我得到以下 64 位数据类型的结果(我在 64 位系统上运行):

uint64_t/size_t/长无符号

Size : 64
Number : 8
Bits : 3 35

以及以下其他长度:

uint32_t/uint16_t/uint8_t

Size : 32 / 16 / 8
Number : 8
Bits : 3

如果更改移位,64 位类型似乎有一个被移位 32 位的“镜像对应项”。当我改变 value 的值时也是如此。这是有原因的还是我错过了什么?

在Win7上使用gcc

最佳答案

size_t 取决于体系结构,因此在 32 位系统上,size_t 可能至少为 32 位宽。在 64 位系统上,它可能至少为 64 位宽。

根据C99 standard :

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers)

也改变

if (value & (1 << ind))

if (value & (1LL << ind))

因为 1 是一个 32 位整数

关于c++ - 位在 size_t 中出现两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25030651/

相关文章:

c - 提取设置为 1 的位索引的最有效方法

c - 位填充 (C)

c++ - 在子字符串上拆分

c++ - 使用 C++ 从文件中读取数据并在命中特定行(字符串)后对特定列求和

C++ ConvexHull of points 算法(及其索引)

c++ - Unsigned Int 溢出

file.txt的Java位处理

C++:我可以编写一个从 T 派生的模板类吗?

c - 将 N 位与接下来的 N 位混合(例如每 4 位)00001111 -> 01010101

Python 异或错误