C -Cuzz by C类型促销从短到INT
continue
I have a question that needs guidance from any expert:
As a value with
short
type is passed as an argument toprintf()
function, it'll be automatically promoted toint
type, that is why theprintf()
function will see the value asint
type instead ofshort
type.So basically
short
type is 16-bits wide, which is0000000000000000
whileint
type is 32-bits wide, which is00000000000000000000000000000000
.Let's say I declare a variable call
num
withshort
type and initialise it with a value of -32, that means the most significant bits of theshort
type will be1
, which is0000000011100000
.When I pass this value to
printf()
, it'll be converted toint
type, so it'll become00000000000000000000000011100000
.In step 4, when it is converted to
int
, the most significant bit is0
.Why, when I use the
%hd
specifier or even the%d
specifier, will it still still prompt me for a negative value instead of a positive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,short 和 int 都是有符号类型,因此它是通过符号扩展而不是 0 字节填充来提升的:
将 MSB 保留为 1,即负数。
您可以通过先将其强制转换为无符号来伪造您所期望的行为,例如
No, short and int are both signed types, so it is promoted by sign extension not 0-byte padding:
leaving the MSB as 1 i.e. negative.
You could fake the behavour you're expecting by casting it unsigned first, e.g.
将short 转换为int 基本上是将short 的最高有效位复制到int 的前16 位中。这就是为什么 int 被打印为负数。如果您不希望出现此行为,请使用
ushort
。Converting a short to an int basically replicates the most significate bit of the short into the top 16 bits of the int. This is why the int is printed as negative. If you do not want this behaviour using a
ushort
.正如你所说,它是转换的,在这种情况下转换意味着知识。也就是说,编译器知道有符号短整型转换是如何工作的。它不只是在前面附加位,它还会创建一个与 Short 具有相同值的新 int。这就是为什么你会得到正确的数字。
As you say it is converted and conversion in this case implies knowlegde. That is the compiler knows how signed short to int conversion work. It does not just append bits in front, it creates a new int with the same value as the short. That's why you get the correct number.