Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my ByteString in BigEndian Format on my x86_64 architecture?

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?

like image 727
Gianluca Corazza Avatar asked Jan 23 '26 07:01

Gianluca Corazza


1 Answers

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.

like image 164
Willem Van Onsem Avatar answered Jan 26 '26 00:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!