简体   繁体   English

C 中 64 位变量的按位移位 >= 32 操作

[英]Bitwise shift >= 32 operation for 64 bit variable in C

I'm trying to make shift operation that is longer than 32 for 64 bit variable.我正在尝试对 64 位变量进行比 32 长的移位操作。 Can someone tell what is messed up with my code.有人可以告诉我的代码出了什么问题。

Processor architechture is AMD64 and development environments are Visual studio Community 2015 and DevC++处理器架构为 AMD64,开发环境为 Visual Studio Community 2015 和 DevC++

My code looks like this:我的代码如下所示:

#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
    uint64_t x = ~0;
    printf("x is %8x \n", x);
    x = ~((uint64_t)(1) << 31);
    printf("x is %8x \n", x);
    x = ~((uint64_t)(1) << 32);
    printf("x is %8x \n", x);
    return 1;
}

Output is:输出是:

x is ffffffff
x is 7fffffff
x is ffffffff

I've been thinking on this for whole morning now.. I'm really a beginner with C on bigger than embedded 8-bit architechtures :)我整个上午都在思考这个问题..我真的是一个初学者,使用比嵌入式 8 位架构更大的 C :)

-Codester -Codester

  • uint64_t x = ~0;

    This code won't work if int is 32 bits.如果int是 32 位,此代码将不起作用。 If you want to set a uint64_t to "all ones" in a portable manner, you need to do uint64_t x = ~(uint64_t)0;如果你想以可移植的方式将uint64_t设置为“所有”,则需要执行uint64_t x = ~(uint64_t)0; . .

  • %8x

    This is not the correct format specifier for uint64_t .这不是uint64_t的正确格式说明符。 You should use PRIx64 from inttypes.h .您应该使用inttypes.h PRIx64 Example:例子:

     #include <inttypes.h> printf("x is %8" PRIx64 "\\n", x);

Adding extra llX to printf format solved my problem:将额外的llX添加到 printf 格式解决了我的问题:

#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
    uint64_t x = ~0;
    printf("x is %8llX \n", x);
    x = ~((uint64_t)(1) << 31);
    printf("x is %8llX \n", x);
    x = ~((uint64_t)(1) << 32);
    printf("x is %8llX \n", x);
    return 1;
}

So many times answer is too simple :P很多时候答案太简单了:P

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

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