Search code examples
ioocamlendianness

What does output_binary_int in OCaml do?


output_binary_int stdout 1101

prints M to stdout.

The doc says "Write one integer in binary format (4 bytes, big-endian)", but I don't really understand what to do with this function.


Solution

  • If you're looking at stdout in a terminal, you are expecting stdout to consist of a sequence of characters.

    The output of output_binary_int is not characters, it is a raw 32-bit integer value. Since a byte is 8 bits, this means it will output 4 bytes. But they arenn't generally going to be bytes that are meaningful when viewed as characters.

    It will make more sense if you send the output to a file, then look at the contents of the file. Something like this:

    $ rlwrap ocaml
            OCaml version 4.10.0
    
    # let ochan = open_out "mybfile";;
    val ochan : out_channel = <abstr>
    # output_binary_int ochan 1101;;
    - : unit = ()
    # close_out ochan;;
    - : unit = ()
    # ^D
    $ od -tx1 mybfile
    0000000    00  00  04  4d
    0000004
    

    As you can see, 4 bytes of binary data were written to the file. The 4 bytes represent the value 1101 in big-endian format.

    If you're not familiar with binary integer representations (forgive me if you are), this means that the value in the file represents the hex value 0x0000044d, which indeed is 1011.

    If the character encoding of your terminal is UTF-8 (which is common), then the output represents two null characters followed by the Control-D character (neither of these has a visual representation), followed by the character with code 0x4d, which indeed is M.