Thomas Kobber Panum
Thomas Kobber Panum

Reputation: 271

Erlang utf-8 hex to decimal

I'm trying to convert the hex 0x80 0x94 (utf-8) into the corresponding decimal value 2014

Is it possible to do that conversion in Erlang?

Upvotes: 2

Views: 627

Answers (3)

Eric des Courtis
Eric des Courtis

Reputation: 5445

The reason you can't convert it is simply that it's not valid UTF-8.

4> io:format("~.2B~n", [16#80]).
10000000
ok
5> io:format("~.2B~n", [16#94]).
10010100
ok

See the Description on this site for details (I am showing you the binary so you can see the binary pattern). But it comes down to 80h being an invalid starting value in UTF-8.

I think what you might want a unicode codepoint from a UTF-8 binary like so:

unicode:characters_to_list(<<"I am a valid utf8 binary">>, utf8).

By the way codepoint 2014 is this character which is 0xDF 0x9E in UTF-8 encoding.

Upvotes: 3

legoscia
legoscia

Reputation: 41527

You can use the binary utf8 conversion for that. Though it looks like your numbers are off:

2> A = <<16#80, 16#94>>.
<<128,148>>
3> <<B/utf8>> = A.
** exception error: no match of right hand side value <<128,148>>

The transformation works both ways, so this is what I'd expect to start with:

5> <<2014/utf8>>.
<<223,158>>

Upvotes: 1

Jack Daniel&#39;s
Jack Daniel&#39;s

Reputation: 2613

I am little confuse with the question. (Sorry about that)...

In erlang Hex numbers are prefixed using 16# so If you have number 16#80 or 16#94 and you want to convert it to decimal value you can use integer_to_list(16#AF8, 10)

Upvotes: 0

Related Questions