转换unsigned int类型以签署诠释三 [英] Convert unsigned int to signed int C

查看:98
本文介绍了转换unsigned int类型以签署诠释三的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图 65529 unsigned int类型转换为签署 INT 。我试着做这样的转换:

I am trying to convert 65529 from an unsigned int to a signed int. I tried doing a cast like this:

unsigned int x = 65529;
int y = (int) x;

仍返回65529时,它应该返回-7。这是为什么?

But y is still returning 65529 when it should return -7. Why is that?

推荐答案

好像你正期待 INT unsigned int类型来是一个16位的整数。这显然​​不是这样。最有可能的,这是一个32位整数 - 这是足够大,以避免环绕,你期待

It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.

请注意,有这样做,因为无/有符号间铸造的值超出范围是实现定义没有C兼容的完全的方式。但是,这仍然会在大多数情况下工作:

Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:

unsigned int x = 65529;
int y = (short) x;      //  If short is a 16-bit integer.

或者:

unsigned int x = 65529;
int y = (int16_t) x;    //  This is defined in <stdint.h>

这篇关于转换unsigned int类型以签署诠释三的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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