当源值无法在目标类型中表示时,将整数转换为有符号类型是根据 cppreference
- 实现定义(C++20 之前)
- 目标类型的唯一值等于源值模 2^n
其中 n 是用于表示目标类型的位数 (C++20 起)
也在 GCC 实现定义的行为,有
为了转换为宽度为 N 的类型,该值会以 2^N 为模进行缩减,以使其处于该类型的范围内;没有发出任何信号。
我猜也有人说同样的话。我的问题是减少/模数结果是否仍然可能超出目标签名类型的范围?假设 signed char c = 255
,255 模 2^8 仍然是 255,没有变化。这个模数结果如何适合目标类型?
这个答案展示了一种方法,首先将值反转并加1,然后在前面添加一个有符号位。我不确定这是否是实际所做的。
解释强调部分的正确/标准方法是什么?
Converting an integer to a signed type when the source value can't be represented in the destination type is according to cppreference
- implementation-defined (until C++20)
- the unique value of the destination type equal to the source value modulo 2^n
where n is the number of bits used to represent the destination type (since C++20)
Also specified in GCC implementation-defined behavior, there is
For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.
I guess there are saying the same thing. My question is isn't the reduced/moduloed result still maybe out of range of the destination signed type? Say signed char c = 255
, 255 modulo 2^8 is still 255, unchanged. How does this moduloed result fit into the destination type?
This answer shows a method to first invert the value and add 1, then prepend a signed bit. I'm not sure if that's what actually have been done.
What's the correct/standard way to interpret the emphasized part?
发布评论
评论(2)
这些引号都不是说采用原始值、应用模运算并将结果用作转换结果。
相反,它们的意思是说,在目标类型中可表示的所有值
v
中,对于某个整数
m
数学等式成立的(唯一)值,其中 < code>s 选择源值。据说,如果s
和v
满足此条件,或者有时也满足此条件,则它们同余模2^n
它们等于模2^n
。对于宽度为
8
的有符号目标的s = 255
,255
不可表示,但-1
可以表示并且 < code>v = -1 满足m = -1
的方程。Neither of these quotes are meant to say that the original value is taken, the modulo operation applied, and the result used as result of the conversion.
Instead they are meant to say that out of all values
v
representable in the destination type, the (unique) one for which the mathematical equalityholds for some integer
m
, withs
the source value, is chosen. It is said thats
andv
are congruent modulo2^n
if they satisfy this condition or sometimes also that they are equal modulo2^n
.For
s = 255
with signed target of width8
,255
is not representable, but-1
is andv = -1
satisfies the equation withm = -1
.255 不在类型范围内(8 位有符号整数)。
重新表述该规则的一种方法是,转换后的结果将与不可表示的结果模 2^n 一致。
-513、-257、-1、255、511 都是模 256 同余。在同余数中,只有 -1 在有符号类型的可表示范围内。
255 isn't within range of the type (of 8 bit signed integer).
One way to re-phrase the rule is that the converted result will be congruent with the unrepresentable result modulo 2^n.
-513, -257, -1, 255, 511 are all congruent modulo 256. Of the congruent numbers, only -1 is within the representable range of the signed type.