Does cast between signed and unsigned int maintain exact bit pattern of variable in memory?

前端 未结 3 855
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 04:41

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) befor

3条回答
  •  天涯浪人
    2020-12-13 05:06

    Casts are used in C to mean both "type conversion" and "type disambiguation". If you have something like

    (float) 3
    

    Then it's a type conversion, and the actual bits change. If you say

    (float) 3.0
    

    it's a type disambiguation.

    Assuming a 2's complement representation (see comments below), when you cast an int to unsigned int, the bit pattern is not changed, only its semantical meaning; if you cast it back, the result will always be correct. It falls into the case of type disambiguation because no bits are changed, only the way that the computer interprets them.

    Note that, in theory, 2's complement may not be used, and unsigned and signed can have very different representations, and the actual bit pattern can change in that case.

    However, from C11 (the current C standard), you actually are guaranteed that sizeof(int) == sizeof(unsigned int):

    (§6.2.5/6) For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements [...]

    I would say that in practice, you can assume it is safe.

提交回复
热议问题