简体   繁体   English

C ++中64位整数的奇怪行为

[英]Strange behaviour of 64 bit integer in C++

I'm quite new to programming, I have recently learnt a little C++ and I am using Visual Studio 2017 Community version. 我对编程很陌生,最近学习了一些C ++,并且正在使用Visual Studio 2017社区版本。

I need to use a 64 bit integer to store a value and carry out some arithmetic operations, however my compiler only allows me to use 32 bits of the "int64" variable I have created. 我需要使用64位整数来存储值并执行一些算术运算,但是我的编译器仅允许我使用已创建的32位“ int64”变量。

Here is an example of some code and the behaviour 这是一些代码和行为的示例

    unsigned __int64  testInt = 0x0123456789ABCDEF;

printf("int value = %016X\n", testInt); // only 32 bits are being stored here? (4 bytes)

printf("size of integer in bytes = %i\n\n", sizeof(testInt)); // size of int is correct (8 bytes)

The value stored in the variable seems to be 0x0000000089ABCDEF. 变量中存储的值似乎为0x0000000089ABCDEF。 Why can I not use all 64 bits of this integer, it seems to act as a 32 bit int? 为什么我不能使用这个整数的所有64位,它看起来像一个32位的int?

Probably I'm missing something basic, but I can't find anything relating to this from searching :( 可能我缺少一些基本知识,但是通过搜索:(

It would be nice if it were just something basic, but it turns out that 64 bit ints are not dealt with consistently on all platforms so we have to lean on macros. 如果这只是一些基本的知识,那会很好,但是事实证明,并非在所有平台上都统一处理64位整数,因此我们不得不依靠宏。

This answer describes the use of PRIu64 , PRIx64 , and related macros included in <inttypes.h> . 此答案描述PRIu64PRIx64<inttypes.h>包含的相关宏的PRIx64 It looks funny like this, but I think the portable solution would look like: 这样看起来很有趣,但是我认为便携式解决方案看起来像:

#include <inttypes.h>
unsigned __int64  testInt = 0x0123456789ABCDEF;
printf("int value = %016" PRIX64 "\n", testInt);

The PRIX64 expands to the appropriate format specifier depending on your platform (probably llX for Visual Studio). PRIX64会根据您的平台(对于Visual Studio可能是llX )扩展为适当的格式说明符。

Format specifier %X takes an unsigned int (probably 32 bit on your system), whereas __int64 corresponds to long long . 格式说明符%X采用无符号int(系统上可能为32位),而__int64对应于long long

Use printf("int value = %016llX\\n", testInt) instead. 改用printf("int value = %016llX\\n", testInt) Documentation can be found, for example, at cppreference.com . 可以在cppreference.com上找到文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM