如何在C中转换或转换unsigned int到int? [英] How to cast or convert an unsigned int to int in C?

查看:1490
本文介绍了如何在C中转换或转换unsigned int到int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的道歉,如果这个问题看起来很奇怪。我调试我的代码,这似乎是问题,但我不知道。

My apologies if the question seems weird. I'm debugging my code and this seems to be the problem, but I'm not sure.

谢谢!

推荐答案

这取决于您想要的行为成为。 int 不能容纳 unsigned int 的许多值。

It depends on what you want the behaviour to be. An int cannot hold many of the values that an unsigned int can.

你可以像往常一样强制转换:

You can cast as usual:

int signedInt = (int) myUnsigned;

但是如果 unsigned 值超过max int 可以保存。这意味着一半的可能的 unsigned 值将导致错误的行为,除非你特别注意它。

but this will cause problems if the unsigned value is past the max int can hold. This means half of the possible unsigned values will result in erroneous behaviour unless you specifically watch out for it.

如果您不必进行转换,您可能需要重新检查如何存储值。

You should probably reexamine how you store values in the first place if you're having to convert for no good reason.

EDIT: ProdigySim在评论中提到,最大值是平台相关的。但您可以使用 INT_MAX UINT_MAX 来访问它。

As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX and UINT_MAX.

对于通常的4字节类型:

For the usual 4-byte types:

4 bytes = (4*8) bits = 32 bits

如果使用所有32位,如 unsigned 值将为2 ^ 32 - 1或 4,294,967,295

If all 32 bits are used, as in unsigned, the maximum value will be 2^32 - 1, or 4,294,967,295.

签名 int 有效地牺牲一个符号位,因此最大值将为2 ^ 31 - 1或 2,147,483,647 。请注意,这是其他值的一半。

A signed int effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647. Note that this is half of the other value.

这篇关于如何在C中转换或转换unsigned int到int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆