Reputation: 310277
I'm trying to read some binary datafiles. The datafiles have a "sentinal" integer written in them which is always -1. I thought that I could use this to check if the machine which wrote the data was big-endian or little-endian, but upon some experimentation it seems this isn't the case. Specifically:
import struct
data=struct.pack('<i',-1)
print (struct.unpack('<i',data)) #(-1,)
print (struct.unpack('>i',data)) #(-1,) ???
Upvotes: 1
Views: 2151
Reputation: 288290
The representation of -1 is the same in big and liddle endian (and two's complement), i.e. (assuming 32 bit)
ffffffff # big endian
ffffffff # little endian
Check with a value such as 0x01020304
, or, if you want to add additional checks, 0x0d0aff00
(0d0a
is the Windows EOL CRLF, ff
will break over 8bit-opaque channels, and 00
will break null-terminated strings).
Upvotes: 4
Reputation: 6992
The value -1 is represented as 0XFFFFFFFF in binary (two's compliment). It will look the same in regardless of endian-ness.
Upvotes: 3