Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml int to binary string conversion

What's the easiest way to convert an Int32.t to binary? For example: -1 -> "\255\255\255\255" ?

Edit: To use extlib, install it with yum and in the toplevel:

#use "topfind";;
#require "extlib";;
like image 396
pbp Avatar asked Mar 19 '12 19:03

pbp


1 Answers

I would suggest using Bitstring for this kind of thing. You can find it here.

For example, in the toplevel:

# #use "topfind";;
# #camlp4o;;
# #require "unix";;
# #require "bitstring.syntax" ;;
# let data = Int32.of_int (-1);;
# let bits = BITSTRING { data: 32 } ;;

then you can perform various conversions on the bitstring including writing it to a binary file or to stdout or to a string:

# Bitstring.string_of_bitstring bits ;;
- : string = "\255\255\255\255"
like image 66
aneccodeal Avatar answered Nov 15 '22 09:11

aneccodeal