转换为 unsigned int,然后转换回来,C
如果我有一个堆栈 S,其中填充有符号整数,我想要执行以下操作: POP 两个值并将其转换为无符号整数,然后将它们加在一起,然后推回一个有符号和。 我做了以下事情,但我不知道它是否正确:
unsigned int x = (unsigned int)pop(S)
unsigned int y = (unsigned int)pop(S)
int sum = x+y
push(S, sum);
pc++
我走在正确的轨道上吗? 另外,有人可以向我解释一下显式强制转换吗? 谢谢。
If I have a stack S, filled with signed ints, I want to do the following:
POP two values and cast it to an unsigned int, then add them together, and then push back a SIGNED sum.
I did the following, but I don't know if it's correct:
unsigned int x = (unsigned int)pop(S)
unsigned int y = (unsigned int)pop(S)
int sum = x+y
push(S, sum);
pc++
Am I on the right track?
Also, can someone explain to me a little bit about explicit casting?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从某种意义上说,您是正确的,您的代码完全按照您所说的去做。真正的问题是这是否是您想要实现的目标。
负数转换为 unsigned int 会变成一个非常大的正数。例如,在转换为 unsigned 后,负数成为可以用 unsigned int 表示的最大正整数(尝试一下!)当您将两个转换为 unsigned 的负数相加时,肯定会发生溢出。如果这确实是您想要做的,那么您的代码肯定会这样做。
You are correct in the sense that your code does precisely what you say it should do. The real question is whether or not that is what you are looking to achieve.
A negative number cast to unsigned int becomes a very large positive number. For example, negative one becomes the largest positive integer that can be expressed in an unsigned int after the cast to unsigned (try it!) When you add two negative numbers that were cast to unsigned, you are guaranteed to get an overflow. If that is indeed what you are trying to do, your code is definitely doing it.