Converting between unsigned and signed int safely

Posted by polemic on Stack Overflow See other posts from Stack Overflow or by polemic
Published on 2014-06-13T05:08:57Z Indexed on 2014/06/13 9:25 UTC
Read the original article Hit count: 242

Filed under:
|
|
|
|

I have an interface between a client and a server where a client sends (1) an unsigned value, and (2) a flag which indicates if value is signed/unsigned. Server would then static cast unsigned value to appropriate type.

I later found out that this is implementation defined behavior and I've been reading about it but I couldn't seem to find an appropriate solution that's completely safe? I've read about type punning, pointer conversions, and memcpy.

Would simply using a union type work? A UnionType containing signed and unsigned int, along with the signed/unsigned flag. For signed values, client sets the signed part of the union, and server reads the signed part. Same for the unsigned part. Or am I completely misunderstanding something?

Side question: how do I know the specific behavior in this case for a specific scenario, e.g. windriver diab on PPC? I'm a bit lost on how to find such documentation.

© Stack Overflow or respective owner

Related posts about c++

Related posts about types