Ocaml int到二进制字符串转换

pbp*_*pbp 6 ocaml type-conversion

什么是最简单的转换Int32为二进制的方法?例如:-1 - >"\ 255\255\255\255"?

编辑:要使用extlib,请使用yum和toplevel安装它:

#use "topfind";;
#require "extlib";;
Run Code Online (Sandbox Code Playgroud)

ane*_*eal 8

我建议使用Bitstring来做这种事情.你可以在这里找到它.

例如,在顶层:

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

然后你可以对bitstring执行各种转换,包括将它写入二进制文件或stdout或字符串:

# Bitstring.string_of_bitstring bits ;;
- : string = "\255\255\255\255"
Run Code Online (Sandbox Code Playgroud)


ygr*_*rek 3

使用extlib

# let io = IO.output_string ();;
val io : string IO.output = <abstr>
# IO.write_i32 io (-1);;
- : unit = ()
# IO.close_out io;;
- : string = "\255\255\255\255"
Run Code Online (Sandbox Code Playgroud)