简体   繁体   中英

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).

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). 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.

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.

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.

Since you're in C land, a cast will be your only way. 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. Also, the value will of course be truncated when converting back, unless you are compiling in a 64-bit environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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