问题描述
值:1,921,222,太大不能存为short,所以出现数值溢出,变成20,678。
谁能演示一下 1,222 变成 20,678 的过程? 如何“环绕”到下一个最低值并从那里开始计数以获得 20,678 提前致谢
解决方法
在 C 语言中,“short”类型有 2 个字节。编译器将每个整数值视为 32 位或 4 字节的“int”类型(这可能因编译器而异)。
short s = 1921222;
在这句话中,您丢失了 2 个字节的数据:
Information that remains in the variable (2 bytes)
^ ^
00000000 00011101 01010000 11000110 -> total data (4 bytes,32 bits)
v v
Information discarded when you put this value in a short type.
换句话说,您“裁剪”了数据,只留下适合指定类型的部分。
01010000 11000110
“01010000 11000110”是 20678。
此站点可以帮助您更好地了解此过程的工作原理: https://hexed.it/