Skip to content

Instantly share code, notes, and snippets.

@jeshan
Last active April 3, 2021 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeshan/bfce96ac13274be2ae40cf53eb4f47d9 to your computer and use it in GitHub Desktop.
Save jeshan/bfce96ac13274be2ae40cf53eb4f47d9 to your computer and use it in GitHub Desktop.
Bi-directional conversion between hex strings and numbers in Prolog
:- use_module(library(clpfd)).
hex_number(Hex, Num) :-
ground(Hex),
!,
string_concat("0x", Hex, HexStr),
number_string(Num, HexStr).
hex_number(Hex, Num) :-
var(Hex),
!,
Num in 0..0xfffffff,
label([Num]),
format(string(Hex), "~16r", Num).
@jeshan
Copy link
Author

jeshan commented Apr 3, 2021

Example outputs:

?- Hex = 'fffff', hex_number(Hex, Num).
Hex = fffff,
Num = 1048575.
?- Num = 98765, hex_number(Hex, Num).
Num = 98765,
Hex = "181cd".
?- hex_number(Hex, Num).
Hex = "0",
Num = 0 ;
Hex = "1",
Num = 1 ;
Hex = "2",
Num = 2 ;
Hex = "3",
Num = 3 ; % etc etc

@jeshan
Copy link
Author

jeshan commented Apr 3, 2021

Code is released in the public domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment