简体   繁体   中英

How to convert long long to unsigned int in C/C++

I am reading from a JSON file using jannson library. The key I am reading for has a value that is of type unsigned int . Jannson cannot recognize unsigned int . So, I am reading the value as a long long . How do I convert this long long value safely to an unsigned int ?

To avoid narrowing conversion errors it's safer to use - numeric_cast

numeric_cast is easy to add to project because used boost code is header only - no need to build boost. This way you can catch exception in case of lost of precision in run-time.

If safety is not the main priority (or you are confident that unsigned int is always sufficient to contain the long long value) than use:

static_cast<unsigned int>(llval)

How to convert long long to unsigned int in C/C++?

Test if the value is in range.
C solution:

#include <stdbool.h>
#include <limits.h>

// return error status 
bool ll_to_u(unsigned *y, long long x) {
  if (x < 0) {
    return true;
  }
  #if LLONG_MAX > UINT_MAX
  if (x > UINT_MAX) {
    return true;
  }
  #endif
  *y = (unsigned) x;
  return false;
}

How do I convert this long long value safely to an unsigned int ?

Like this:

long long input = ...
if (input < 0)
    throw std::runtime_error("unrepresentable value");
if (sizeof(unsigned) < sizeof(long long)
&& input > static_cast<long long>(std::numeric_limits<unsigned>::max()))
    throw std::runtime_error("unrepresentable value");
return static_cast<unsigned>(input);

You can use any other error handling method of your choice if you don't like exceptions.

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