声明64位变量用C [英] Declaring 64-bit variables in C
问题描述
我有一个问题。
uint64_t中VAR = 1; //这是... 000000 00001吧?
在我的code这个作品:
VAR ^(1 <<;&LT; 43)
但它是如何知道1应该在64位?应该不是我写这篇文章呢?
VAR ^((uint64_t中)1 LT;&LT; 43)
当你认为,1是一个纯签署 INT
(这可能你的平台上为32位宽2的补运算),所以是43,所以任何机会<$ C $ C> 1&LT;&LT; 43 导致溢出:在事实,如果两个参数的数据类型的 INT
运营规则规定,其结果将是一个 INT
以及
不过,在C符号整数溢出是未定义行为,所以原则上任何的行可能发生。你的情况,可能是编译器发出code来执行在64位寄存器,移位,所以的靠运气的它似乎工作;让你应该用你写的第二种形式,或者,可以通过指定有保证的,正确的结果 1
为无符号长长
文字使用 ULL
后缀(无符号长长
是保证的至少 64位)。
VAR ^(1ULL&LT;&LT; 43)
I have a question.
uint64_t var = 1; // this is 000000...00001 right?
And in my code this works:
var ^ (1 << 43)
But how does it know 1 should be in 64 bits? Shouldn’t I write this instead?
var ^ ( (uint64_t) 1 << 43 )
As you supposed, 1 is a plain signed int
(which probably on your platform is 32 bit wide in 2's complement arithmetic), and so is 43, so by any chance 1<<43
results in an overflow: in facts, if both arguments are of type int
operator rules dictate that the result will be an int
as well.
Still, in C signed integer overflow is undefined behavior, so in line of principle anything could happen. In your case, probably the compiler emitted code to perform that shift in a 64 bit register, so by luck it appears to work; to get a guaranteed-correct result you should use the second form you wrote, or, in alternative, specify 1
as an unsigned long long
literal using the ull
suffix (unsigned long long
is guaranteed to be at least 64 bit).
var ^ ( 1ULL << 43 )
这篇关于声明64位变量用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!