gpt4 book ai didi

C++右移、异或问题

转载 作者:行者123 更新时间:2023-11-30 01:49:31 25 4
gpt4 key购买 nike

我有这个示例代码:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#ifndef uint32
#define uint32 unsigned long int
#endif
#define L(a) printf("\n%x >> 1 = %x", a, a>>1)
int _tmain(int argc, _TCHAR* argv[])
{
uint32 a = 2941362065;
uint32 b = 509727776;
uint32 c = a ^ b;
L(a^b);
printf("\n%x >> 1 = %x", c , c>>1);
return 0;
}

我的问题是 L(a) 返回

b1304bb1 >> 1 = a0617581

同时

printf("\n%x >> 1 = %x", c , c>>1);

返回

b1304bb1 >> 1 = 589825d8

最后一个值是 Windows 计算器返回的正确值。此代码在 WinXP 32 上运行。有什么想法吗?

最佳答案

L(a^b) becomes printf("\n%x >> 1 = %x", a^b, a^b>>1)

>> 的优先级为 5 而 ^ 为 9(参见 this ),这意味着上面的调用给出与以下相同的结果(注意额外的括号):

printf("\n%x >> 1 = %x", a^b, a^(b>>1))

您应该通过在参数周围添加括号来更改 L 定义:

#define L(a) printf("\n%x >> 1 = %x", (a), (a)>>1)

最好使用函数而不是 L 宏。

关于C++右移、异或问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com