简体   繁体   English

如何在C / C ++中将long long转换为unsigned int

[英]How to convert long long to unsigned int in C/C++

I am reading from a JSON file using jannson library. 我正在使用jannson库从JSON文件读取。 The key I am reading for has a value that is of type unsigned int . 我正在读取的键的值类型为unsigned int Jannson cannot recognize unsigned int . Jannson无法识别unsigned int So, I am reading the value as a long long . 因此,我正在long long阅读此值。 How do I convert this long long value safely to an unsigned int ? 如何将这个long long值安全地转换为unsigned int

To avoid narrowing conversion errors it's safer to use - numeric_cast 为避免缩小转换错误,使用更安全 -numeric_cast

numeric_cast is easy to add to project because used boost code is header only - no need to build boost. numeric_cast易于添加到项目中,因为使用的增强代码仅是标头-无需构建增强。 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: 如果安全性不是主要优先级(或者您确信unsigned int总是足以包含long long值),则比使用安全性高:

static_cast<unsigned int>(llval)

How to convert long long to unsigned int in C/C++? 如何在C / C ++中将long long转换为unsigned int?

Test if the value is in range. 测试该值是否在范围内。
C solution: C解决方案:

#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 ? 如何将这个long long值安全地转换为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. 如果您不喜欢例外,则可以使用其他选择的错误处理方法。

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

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