较大的整数在C较小的无符号的类型转换 [英] Larger integer to smaller unsigned type conversion in C

查看:126
本文介绍了较大的整数在C较小的无符号的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过K&放goint;河我有以下的197页上线的理解问题(第A6)


  

积分转换:任何整数
  通过转换为一个给定的无符号类型
  寻找最小的非负
  值,该值是一致于
  整数,模比一个更多
  可重新presented最大值
  在无符号的类型。


任何机构可以在详细一点解释。
谢谢


解决方案

  

任何整数被找到最小的非负值,该值是一致于整数,模比可以重新在无符号类型psented $ P $最大值多一个转换为一个给定的无符号类型。


让我们来这点点滴滴,并从向后:


  

什么是可以重新在无符号类型宽度的n位的psented $ P $最大值?


  2 ^(N) -  1。


  

这是比该值多一个?


  2 ^ N。


  

如何转换发生?


  unsigned_val = signed_val%2 ^ N

现在,为什么部分:标准并不强制什么位重新presentation使用。因此,行话。在一个二的补码重新presentation - 这是迄今为止最常用的 - 这种转换不改变的位模式(除非有一个截断,当然)

从标准参照积分转换为进一步的细节。

I was goint through k & r. I was having problem in understanding following lines on page 197(section A6)

Integral conversions: any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.

Can any body explain this in a bit detail. Thanks

解决方案

any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.

Let's take this bit by bit and from backwards:

What is the largest value that can be represented in the unsigned type of width n bits?

2^(n) - 1.

What is one more than this value?

2^n.

How does the conversion take place?

unsigned_val = signed_val % 2^n

Now, the why part: The standard does not mandate what bit representation is used. Hence the jargon. In a two's complement representation -- which is by far the most commonly used -- this conversion does not change the bit pattern (unless there is a a truncation, of course).

Refer to Integral Conversions from the Standard for further details.

这篇关于较大的整数在C较小的无符号的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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