I've got some c++ code that's requiring me to cast an immediate in an assignment statement. The casting makes the code more difficult to read and I was hoping there was a way around this.
我有一些c++代码需要我在赋值语句中强制转换。强制转换使代码更难于阅读,我希望有办法解决这个问题。
uint64_t shifted_val = (uint64_t)1 << 50;
If I write this code without the cast, shifted_val
gets set to 0, I assume because it's treating the 1
immediate as a 32-bit value. Is there something I'm missing so that I can write this without casting?
如果我在没有cast的情况下编写这段代码,shifted_val将被设置为0,我假设因为它将1作为一个32位的值处理。有什么东西我遗漏了,我可以写这没有铸造?
3 个解决方案
#1
5
One way to do it is to adopt a habit of performing the calculations within the recipient variable itself
一种方法是养成在接收变量本身中执行计算的习惯
uint64_t shifted_val = 1;
shifted_val <<= 50;
This will solve the issue naturally, without requiring you to hardcode additional type references into the expression (like type casts or type-specific suffixes).
这将自然地解决这个问题,而不需要将额外的类型引用硬编码到表达式中(比如类型转换或特定于类型的后缀)。
#2
6
You can do:
你能做什么:
uint64_t shifted_val = 1ull << 50;
If you think the syntax is also close to casting then you can do:
如果您认为语法也接近于强制转换,那么您可以这样做:
uint64_t a = 1;
uint64_t shifted_val = a << 50;
#3
2
The constant needs to be treated as a 64 bit value, so there needs to be some way of specifying that.
常量需要被当作64位值来处理,因此需要某种方式来指定它。
You could specify it as 1ULL
, which tells the compiler the constant is a unsigned long long
, however that may not necessarily be 64 bit, so you're better off with the cast to be more portable.
您可以将它指定为1ULL,它告诉编译器这个常量是一个无符号的长时间,然而,这可能不一定是64位,所以您最好使用cast来更便于携带。
#1
5
One way to do it is to adopt a habit of performing the calculations within the recipient variable itself
一种方法是养成在接收变量本身中执行计算的习惯
uint64_t shifted_val = 1;
shifted_val <<= 50;
This will solve the issue naturally, without requiring you to hardcode additional type references into the expression (like type casts or type-specific suffixes).
这将自然地解决这个问题,而不需要将额外的类型引用硬编码到表达式中(比如类型转换或特定于类型的后缀)。
#2
6
You can do:
你能做什么:
uint64_t shifted_val = 1ull << 50;
If you think the syntax is also close to casting then you can do:
如果您认为语法也接近于强制转换,那么您可以这样做:
uint64_t a = 1;
uint64_t shifted_val = a << 50;
#3
2
The constant needs to be treated as a 64 bit value, so there needs to be some way of specifying that.
常量需要被当作64位值来处理,因此需要某种方式来指定它。
You could specify it as 1ULL
, which tells the compiler the constant is a unsigned long long
, however that may not necessarily be 64 bit, so you're better off with the cast to be more portable.
您可以将它指定为1ULL,它告诉编译器这个常量是一个无符号的长时间,然而,这可能不一定是64位,所以您最好使用cast来更便于携带。