简体   繁体   English

如何将未签名的转换为uint64_t?

[英]How do I convert an unsigned to uint64_t?

I've got an unsigned and would like to convert that to an uint64_t (and back if possible). 我有一个unsigned ,想将其转换为uint64_t (如果可能,请返回)。

How do I do that? 我怎么做? If possible, I would like to avoid depending on undefined behaviour. 如果可能的话,我想避免依赖未定义的行为。

Thanks! 谢谢!

The conversion to unsigned integer types from any integer types is completely defined by the standard (section 6.3.1.3, paragraph 2). 从任何整数类型到无符号整数类型的转换完全由标准定义(第6.3.1.3节,第2段)。 If the value can be represented in the target type, it is preserved, otherwise the value is reduced modulo 2^WIDTH , where WIDTH is the width (number of value bits) of the target type. 如果该值可以用目标类型表示,则将其保留,否则该值将以2^WIDTH模,其中WIDTH是目标类型的宽度(值位数)。

For instance: 例如:

const uint64_t bigvalue = (uint64_t) 42u;

Not sure if the cast is even necessary, since this doesn't loose information. 不确定是否需要强制转换,因为这不会丢失信息。 The opposite: 相反:

const unsigned int smallvalue = (unsigned int) bigvalue;

will need the cast, since it's (probably, assuming int < uint64_t ) a more narrow type. 将需要uint64_t类型转换,因为它(可能是假设int < uint64_t )是一个更窄的类型。

Note: I mean "need" in a weak sense; 注意:我的意思是“需要”,意思是“弱”。 since there is a risk of losing information when converting to a more narrow type, it's likely that compilers will warn. 由于在转换为更窄的类型时可能会丢失信息,因此编译器可能会发出警告。 The cast adds a sense of "I know what I'm doing" which is how such warnings are typically silenced. 演员表增加了一种“我知道我在做什么”的感觉,这通常是使此类警告静音的方式。

You can do it with typecasting: 您可以通过类型转换来做到这一点:

uint64_t new = (uint64_t) old;

Where old is your unsigned int. old是你的unsigned int类型。

Since you're in C land, a cast will be your only way. 由于您在C地带,因此强制转换是唯一的方法。 Simply do 简单地做

uint64_t foo = (uint64_t)myVar;

Or, in reverse 或者,相反

unsigned int bar = (unsigned int)foo;

Your compiler should pick up the conversion automatically though, although in the case of a uint64_t -> unsigned int , you should get a warning regarding truncation. 尽管在uint64_t > unsigned int的情况下,您的编译器应该自动进行转换,但是您会收到有关截断的警告。 Also, the value will of course be truncated when converting back, unless you are compiling in a 64-bit environment. 此外,除非在64位环境中进行编译,否则在转换回该值时,该值当然会被截断。

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

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