将 long long 转换为 int 如何工作?
How does converting long long to int work?
例如我有以下内容:
#include <iostream>
int main()
{
long long a = 2346436346346346;
int b = a;
//int b = static_cast<int>(a) //same result
std::cout << a << "\n" << b;
std::cin.get();
}
输出:
2346436346346346
1223261034
b
根据什么逻辑取该值?
对有符号整数类型的溢出赋值的结果是实现定义的:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and
bit-field width); otherwise, the value is implementation-defined.
(N4140 中的 4.7 条款 3)
所以您必须询问提供您的实现的人他们所说的结果是什么,C++ 标准对此没有任何说明。
By what logic does b take that value?
它是实现定义的,在您的情况下该值被截断:
2346436346346346 in binary is:
0000000000001000 0101011000010010 0100100011101001 0111101101101010
1223261034 in binary is:
0100100011101001 0111101101101010
根据标准4.7\p3积分转换[conv.integral](强调我的):
If the destination type is signed, the value is unchanged if it can be
represented in the destination type; otherwise, the value is
implementation-defined
例如我有以下内容:
#include <iostream>
int main()
{
long long a = 2346436346346346;
int b = a;
//int b = static_cast<int>(a) //same result
std::cout << a << "\n" << b;
std::cin.get();
}
输出:
2346436346346346
1223261034
b
根据什么逻辑取该值?
对有符号整数类型的溢出赋值的结果是实现定义的:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
(N4140 中的 4.7 条款 3)
所以您必须询问提供您的实现的人他们所说的结果是什么,C++ 标准对此没有任何说明。
By what logic does b take that value?
它是实现定义的,在您的情况下该值被截断:
2346436346346346 in binary is:
0000000000001000 0101011000010010 0100100011101001 0111101101101010
1223261034 in binary is:
0100100011101001 0111101101101010
根据标准4.7\p3积分转换[conv.integral](强调我的):
If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined