Home > Net >  Why is my ByteString in BigEndian Format on my x86_64 architecture?
Why is my ByteString in BigEndian Format on my x86_64 architecture?

Time:10-18

This code:

import Data.Binary
import qualified Data.ByteString.Internal as BS (c2w, w2c)
import qualified Data.ByteString.Lazy as B
import Data.Int

main :: IO ()
main = do
  B.putStr $ encode $ (0x01020304 :: Int32)

produces this output on my machine (run through xxd):

00000000: 0102 0304                                ....

which tells me that it is output in big endian order, but I have an x86_64 system, so... what's going on?

CodePudding user response:

The Data.Binary module specifies in the documentation:

Values encoded using the Binary class are always encoded in network order (big endian) form, and encoded data should be portable across machine endianness, word size, or compiler version. For example, data encoded using the Binary class could be written on any machine, and read back on any another.

It thus does not work with then endianess of the machine, but always with big endian, such that encoding an object to a ByteString, can also be decoded with another machine.

  • Related