junius
junius

Reputation: 570

Convert Hexadecimal String to Integer

All I want is a predicate of the form

parse_hex(H, N).

which converts between a hexadecimal string and prolog integers. I could implement this myself, obviously, but I am wondering if there is a built in. I haven't been able to find one but it seems like there must be a way to do this.

Upvotes: 1

Views: 187

Answers (1)

Paulo Moura
Paulo Moura

Reputation: 18663

Given that standard Prolog supports hexadecimal numbers, if by string you mean a Prolog atom:

parse_hex(H, N) :-
    atom_concat('0x', H, HexaAtom),
    atom_codes(HexaAtom, HexaCodes),
    number_codes(N, HexaCodes).

If you really have a string instead of an atom, see your Prolog documentation on converting it into an atom. E.g. SWI-Prolog provides an atom_string/2 bi-directional built-in predicate.

Sample call:

?- parse_hex('ff', N).
N = 255.

Upvotes: 1

Related Questions