在这种情况下如何使用负零?

发布于 2024-09-26 16:56:42 字数 75 浏览 1 评论 0原文

struct in_addr ipv4;

ipv4.s_addr = (uint32_t)(-0)
struct in_addr ipv4;

ipv4.s_addr = (uint32_t)(-0)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

筱果果 2024-10-03 16:56:42

这很奇怪,通常算术是通过 二进制补码 实现的,所以你实际上并没有负数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 as 0xFFFFFFFF so you would have 255.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 you 0x00000000.

月亮是我掰弯的 2024-10-03 16:56:42

这没有多大意义,因为标准规定了整数类型的精确宽度

这些类型是可选的。然而,如果
一个实现提供了整数
宽度为 8、16、32 或 64 的类型
位,无填充位,并且(对于
有符号类型)有一个二
补充表示,它应
定义对应的typedef
名称。

因此,首先,任何这些有符号类型都没有负零,而无符号类型则更少。无论如何,对于分配,您显示一个简单的 0 也不错,如果您想挑剔的话,也可以显示 UINT32_C(0)

This makes not much sense, since the standard says about the exact width integer types

These types are optional. However, if
an implementation provides integer
types with widths of 8, 16, 32, or 64
bits, no padding bits, and (for the
signed types) that have a two's
complement representation, it shall
define the corresponding typedef
names.

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, or UINT32_C(0) if you want to be picky.

旧时浪漫 2024-10-03 16:56:42

它将用于获取无符号整数的有符号值,或者比有符号整数的最大值大一。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文