简体   繁体   中英

Are signed binary representations portable between architectures?

I would like to send signed integers across a network in a character stream, and/or save them to disk in a portable binary representation.

Is the ordinary binary representation that gets stored in memory when I assign a variable (I'm using long long, which is 64 bits, signed), considered to be portable between different machine architectures and operating systems?

For example, is the binary representation of a signed negative long long integer the same on an ARM machine as on an x86 machine, and if so, is it considered good/acceptable practice to take advantage of the fact?

Edit: We're already addressing the issue of byte order by using integer operations to deconstruct the integer into chars from the LSB side. My question is whether the 2's complement signed representation is consistent across architectures.

In short: NO , you cannot rely on binary compatibility across architectures. Different host machines use different byte orders (that's called endianess ).

To transport numbers over network it's general consent to use big endian format (aka network byte order). If both machines use also big endian format, they'll take advantage of this automatically. For the ARM architecture byte orders need to be converted.

To convert from network to host byte order and vice versa you can use the ntohl() , ntohs() , htonl() , htons() function family from arpa/inet.h .

Integers are not "portable by design" in C/C++; you might encounter endianness issues. This is unrelated to them being signed or unsigned.

If you are writing this software, make sure to send your integers in a known byte order. The receiving part needs to read them in the same order, performing an endianness conversion when necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM