简体   繁体   English

超出范围时转换为签名类型行为

[英]Conversion to signed type behavior when out of range

Converting an integer to a signed type when the source value can't be represented in the destination type is according to cppreference当源值不能在目标类型中表示时,将 integer 转换为有符号类型是根据cppreference

  • implementation-defined (until C++20)实现定义的(直到 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)等于源值模 2^n的目标类型的唯一值,其中 n 是用于表示目标类型的位数 (C++20 起)

Also specified in GCC implementation-defined behavior, there isGCC实现定义的行为中也指定了,有

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type;为了转换为宽度为 N 的类型,该值将以2^N 为模减少到该类型的范围内; 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.假设signed char c = 255 ,255 模 2^8 仍然是 255,没有变化。 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. This answer显示了一种方法,该方法首先反转值并加 1,然后添加一个带符号的位。 I'm not sure if that's what actually have been done.我不确定这是否真的已经完成了。

What's the correct/standard way to interpret the emphasized part?解释强调部分的正确/标准方法是什么?

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 equality相反,它们的意思是说在目标类型中可表示的所有值v中,(唯一的)一个满足数学等式的

s + m * 2^n = v

holds for some integer m , with s the source value, is chosen.选择了一些 integer m ,其中s是源值。 It is said that s and v are congruent modulo 2^n if they satisfy this condition or sometimes also that they are equal modulo 2^n .如果 s 和 v 满足此条件,则称sv2^n一致,或者有时它们也等于模2^n

For s = 255 with signed target of width 8 , 255 is not representable, but -1 is and v = -1 satisfies the equation with m = -1 .对于s = 255和宽度为8的带符号目标, 255不可表示,但-1是并且v = -1满足m = -1的等式。

Say signed char = 255U, 255 modulo 2^8 is still 255假设 signed char = 255U,255 模 2^8 仍然是 255

255 isn't within range of the type (of 8 bit signed integer). 255 不在类型范围内(8 位有符号整数)。

One way to re-phrase the rule is that the converted result will be congruent with the unrepresentable result modulo 2^n.重新表述规则的一种方法是转换后的结果将与不可表示的结果模 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. -513、-257、-1、255、511都是全等模256。全等数中,只有-1在有符号类型的可表示范围内。

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

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