Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert numbers among hex, oct, decimal and binary in OCaml?

Tags:

ocaml

What is the general way to convert numbers among hex, oct and binary in OCaml?

For example, how to convert hex 4294967276 (FFFFFFFC) to decimal number?

Thanks!

Nick

like image 438
Nick Avatar asked Mar 20 '13 13:03

Nick


1 Answers

It's not clear what you're asking. Numbers are just numbers, really. They don't have a base (ignoring the hardware representation). The time you have a base is when you convert numbers to and from strings. To interpret a string as a decimal integer you can use int_of_string. For other bases, you can use Scanf.sscanf. To convert a number to a decimal string you can use string_of_int. For other bases, you can use Printf.sprintf.

# int_of_string "345";;
- : int = 345
# Scanf.sscanf "FC" "%x" (fun x -> x);;
- : int = 252
# string_of_int 345;;
- : string = "345"
# Printf.sprintf "%X" 252;;
- : string = "FC"
# 

Granted, Scanf.sscanf is fairly cumbersome to use. But I don't know of any other conversion functions in the OCaml Standard Library.

Update

As observed by barti_ddu, if you don't mind adding a prefix to your input string you can use int_of_string for all 4 of the bases you mention:

# int_of_string "0xFC";;
- : int = 252
# int_of_string "0o374";;
- : int = 252
# int_of_string "0b11111100";;
- : int = 252

(Or maybe your input already has the prefix, in which case this is a much simpler solution.)

like image 93
Jeffrey Scofield Avatar answered Nov 15 '22 11:11

Jeffrey Scofield