是否投在内存变量的签署和unsigned int保持精确的位模式之间? [英] Does cast between signed and unsigned int maintain exact bit pattern of variable in memory?

查看:116
本文介绍了是否投在内存变量的签署和unsigned int保持精确的位模式之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过插座来传递一个32位有符号整数 X 。为了使接收器知道预期的字节顺序,我打电话 htonl(X)发送之前。 htonl 需要一个 uint32_t的不过,我想可以肯定,当我投会发生什么我的 int32_t uint32_t的

I want to pass a 32-bit signed integer x through a socket. In order that the receiver knows which byte order to expect, I am calling htonl(x) before sending. htonl expects a uint32_t though and I want to be sure of what happens when I cast my int32_t to a uint32_t.

int32_t x = something;
uint32_t u = (uint32_t) x;

是不是总是如此,在字节x U 每个将是完全一样的吗?有关转换回什么:

Is it always the case that the bytes in x and u each will be exactly the same? What about casting back:

uint32_t u = something;
int32_t x = (int32_t) u;

我认识到,投大无符号值的负值,但这并不重要,因为我只是铸造回到另一端。但是,如果与实际字节投混乱,然后我不能肯定回来铸造将返回相同的值。

I realise that negative values cast to large unsigned values but that doesn't matter since I'm just casting back on the other end. However if the cast messes with the actual bytes then I can't be sure casting back will return the same value.

推荐答案

在一般情况下,用C铸造是在价值观方面指定,而不是位模式 - 前者将是preserved(如果可能),但后者未必如此。以二的补重新presentations的情况下没有填充 - 这是强制性的固定用整数类型 - 这种区别并不重要,铸造确实将一个空操作

In general, casting in C is specified in terms of values, not bit patterns - the former will be preserved (if possible), but the latter not necessarily so. In case of two's complement representations without padding - which is mandatory for the fixed-with integer types - this distinction does not matter and the cast will indeed be a noop.

不过,即使从符号到无符号的转换会改变的位模式,将其转换回再次将恢复原值 - 需要提醒的是超出范围的符号到符号的转换是实现定义的,并且可能引发上溢出的信号。

But even if the conversion from signed to unsigned would have changed the bit pattern, converting it back again would have restored the original value - with the caveat that out-of-range unsigned to signed conversion is implementation-defined and may raise a signal on overflow.

有关完整的便携性(这可能会矫枉过正),你需要使用双关语的类型,而不是转换。这可以以两种方式之一来进行:

For full portability (which will probably be overkill), you'll need to use type punning instead of conversion. This can be done in one of two ways:

通过指针的类型转换,即

Via pointer casts, ie

uint32_t u = *(uint32_t*)&x;

你应该小心,因为它可能会违反有效打字规则(不过是罚款整数类型的符号/无符号的变体)或通过工会,即

which you should be careful with as it may violate effective typing rules (but is fine for signed/unsigned variants of integer types) or via unions, ie

uint32_t u = ((union { int32_t i; uint32_t u; }){ .i = x }).u;

这也可以用来例如,从转换双 uint64_t中,你可能无法与指针类型转换做如果你想避免不确定的行为。

which can also be used to eg convert from double to uint64_t, which you may not do with pointer casts if you want to avoid undefined behaviour.

这篇关于是否投在内存变量的签署和unsigned int保持精确的位模式之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆