如果 long var 被初始化为 0,我假设每个字节的值都应该为 0。(对于 __int128 也是如此)
这是一段测试代码:
int64_t i64 = { 0 };
auto addr = &i64;
LOG(INFO) << "i64 address=" << addr << ": " << i64;
for (int i = 0; i < sizeof(i64); i++) {
LOG(INFO) << addr + i << ": byte=" << (int)*reinterpret_cast<int8_t*>(addr + i);
}
我希望看到每个字节都为 0。然而,情况并非如此,这是在 "Mac Mojave 10.14.6"上用 clang 运行的结果
Apple clang version 11.0.0 (clang-1100.0.33.12) Target: x86_64-apple-darwin18.7.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
I1113 23:26:05.741184 103323072 TestCommon.cpp:498] i64 地址=0x7ffeeb589a90:0
I1113 23:26:05.741191 103323072 TestCommon.cpp:500] 0x7ffeeb589a90: byte=0
I1113 23:26:05.741196 103323072 TestCommon.cpp:500] 0x7ffeeb589a98: byte=0
I1113 23:26:05.741201 103323072 TestCommon.cpp:500] 0x7ffeeb589aa0: byte=0
I1113 23:26:05.741205 103323072 TestCommon.cpp:500] 0x7ffeeb589aa8: 字节=1
I1113 23:26:05.741210 103323072 TestCommon.cpp:500] 0x7ffeeb589ab0: byte=0
I1113 23:26:05.741214 103323072 TestCommon.cpp:500] 0x7ffeeb589ab8: 字节=-126
I1113 23:26:05.741219 103323072 TestCommon.cpp:500] 0x7ffeeb589ac0: byte=96
I1113 23:26:05.741223 103323072 TestCommon.cpp:500] 0x7ffeeb589ac8: byte=1
这可能是什么原因?它与内存顺序或 CPU 缓存同步有关吗?或者这些是 0 长的合法字节值?
但是,如果我使用 union 来包装它,我可以看到所有字节的值为零:
union U {
int128_t a;
int8_t b[16];
};
U u = { 0 };
LOG(INFO) << "value=" << *reinterpret_cast<int64_t*>(u.b + 8);
for (int i = 0; i < 16; i++) {
LOG(INFO) << "byte=" << (int)u.b[i];
}
输出:
I1113 23:26:05.757899 103323072 TestCommon.cpp:539] 值=0
I1113 23:26:05.757905 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757910 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757915 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757920 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757925 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757928 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757932 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757936 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757942 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757946 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757951 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757956 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757959 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757966 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757970 103323072 TestCommon.cpp:541] byte=0
I1113 23:26:05.757975 103323072 TestCommon.cpp:541] byte=0
感谢任何见解和意见...
最佳答案
你的问题是:
auto addr = &i64;
创造:
int64_t* addr = &i64;
因此,每次您增加 addr
,它都会增加 sizeof int64_t
。
你想要更像是:
uint8_t* addr = reinterpret_cast<uint8_t*>(&i64);
关于c++ - 8 字节或 16 字节数字的字节值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58861731/