Bromo Programmer
Bromo Programmer

Reputation: 670

How to convert numbers back to string in Elixir?

I'm new to elixir and I'm excited. I did play around with Binary like below in IEX terminal.

iex(34)> world = <<119,111,114,108,100>>
"world"

iex(35)> <<x::size(40)>> = world
"world"

iex(36)> x
512970878052

I really don't know what number 512970878052 represents, but I really want to convert it back to a word "world". How can I do that?

Thanks :)

Upvotes: 2

Views: 769

Answers (1)

Dogbert
Dogbert

Reputation: 222060

You can use the exact same expression to convert back!

iex(1)> world = <<119,111,114,108,100>>
"world"
iex(2)> <<x::size(40)>> = world
"world"
iex(3)> x
512970878052
iex(4)> <<x::size(40)>>
"world"

(You can also write just <<x::40>> instead of <<x::size(40)>> in both cases.)


I really don't know what number 512970878052 represents

That's the integer represented by the bytes [119, 111, 114, 108, 100] when interpreted as an unsigned big-endian integer, i.e.

iex(5)> use Bitwise
Bitwise
iex(6)> 119 <<< 32 ||| 111 <<< 24 ||| 114 <<< 16 ||| 108 <<< 8 ||| 100
512970878052

Upvotes: 7

Related Questions