在这种情况下如何使用负零?
struct in_addr ipv4;
ipv4.s_addr = (uint32_t)(-0)
struct in_addr ipv4;
ipv4.s_addr = (uint32_t)(-0)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
struct in_addr ipv4;
ipv4.s_addr = (uint32_t)(-0)
struct in_addr ipv4;
ipv4.s_addr = (uint32_t)(-0)
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
这很奇怪,通常算术是通过 二进制补码 实现的,所以你实际上并没有负数
0
的表示。在补码版本中,负数
0
存储为0xFFFFFFFF
,因此转换后您将得到255.255.255.255
转换为 unsigned int 后的 ipv4 地址。在正常架构中,使用
-0
将其转换为无符号 int 应该只会给出0x00000000
。That's strange, usually arithmetic is implemented through Two's Complement so you don't effectively have a negative representation of
0
.In a One's Complement version the negative
0
is instead stored as0xFFFFFFFF
so you would have255.255.255.255
when converted to an ipv4 address after the cast to unsigned int.While in a normal architecture using
-0
to cast it to an unsigned int should just give you0x00000000
.这没有多大意义,因为标准规定了整数类型的精确宽度
因此,首先,任何这些有符号类型都没有负零,而无符号类型则更少。无论如何,对于分配,您显示一个简单的
0
也不错,如果您想挑剔的话,也可以显示UINT32_C(0)
。This makes not much sense, since the standard says about the exact width integer types
So first of all there is no negative zero for any of these signed types and then even less for the unsigned ones. In any case for the assignment that you show a simple
0
would be as good, orUINT32_C(0)
if you want to be picky.它将用于获取无符号整数的有符号值,或者比有符号整数的最大值大一。
uint32_t
会将其转换为无符号整数,而-0
将强制其为负数,翻转有符号位,并返回翻转后的无符号值。本文解释了有符号整数。
It would be used to get the signed value of the unsigned integer, or, one more than the maximum value of a signed integer.
The
uint32_t
would be casting it to an unsigned integer, while the-0
would be forcing it to be negative, flipping the signed bit, and returning the unsigned value with it flipped.This article explains signed integers.