c - are signed integer and unsigned integer one-one mapping with each other? -
i want make ip-port pair search key, have following function
int64_t make_pair(u_int32_t ip, u_int16_t port) { u_int64_t ip_u64 = ip; ip_u64 = ip_u64 << 16; int64_t ip_port_pair = (int64_t)(ip_u64 + (u_int64_t)port); return ip_port_pair; }
indeed, want transform u_int64_t int64_t because not convenient unsigned integer compare value. i'm afraid cast u_int64_t int64_t not one-one mapping , there conflicts or search error.
so want ask cast u_int64_t int64_t not one-one mapping or not? thanks!
the c standard guarantees int64_t
uses two's-complement representation no padding bits, it's implicitly guaranteed there's one-to-one mapping. (i believe it's still possible negative value trap representation, that's unlikely in practice. unlike ordinary signed integer types, intn_t
types cannot make negative value trap representation; 2n possible representations well-defined , have distinct values.)
on other hand, there's no guarantee int64_t
exists.
a conversion uint64_t
int64_t
yields implementation-defined result values outside range of int64_t
. result 1 you'd expect, produced reinterpreting representation, it's not guaranteed.
so in practice, can away converting between int64_t
, uint64_t
.
but why need to? it's "because not convenient unsigned integer compare value". what's inconvenient it? relational operators defined both signed , unsigned types.
Comments
Post a Comment