我希望能够将 Elixir 字符串(二进制)转换为base10整数。
我已经能够通过以下方式做到这一点......
<<104, 101, 108, 108, 111>> # equal to string "hello"
|> Base.encode16()
|> Integer.parse(16)
{448378203247, ""}
以上做了我所追求的,但感觉有点像黑客。我想...
最佳答案
由于 Elixir 字符串只是二进制文件,您可以使用 erlang :binary.decode_unsigned
函数将二进制数字转换为整数
从文档中
http://erlang.org/doc/man/binary.html#decode_unsigned-1
iex> :binary.decode_unsigned("hello")
448378203247
iex> :binary.encode_unsigned(448378203247)
"hello"
本质上,
hello
的ascii值是<<104, 101, 108, 108, 111>>
当从十进制转换为十六进制时可以写成
<<68, 65, 6C, 6C, 6F>>
或二进制为
<01101000, 01100101, 01101100, 01101100, 01101111>
这是一系列存储为的字节
68656C6C6F
十六进制或01101000_01100101_01101100_01101100_01101111
二进制其 decimal(base-10) 值将是
448378203247
iex> Integer.to_string(448378203247, 16)
"68656C6C6F"
iex> Integer.to_string(448378203247, 2)
"110100001100101011011000110110001101111"
# each byte separated by _ is
# "1101000_01100101_01101100_01101100_01101111"
# missing a leading zero at the left, which doesn't change the value
编辑:添加二进制示例,
此外,可以使用两个十六进制数字来完美地表示一个字节(编码 16 个值需要 4 位,0 到 15)
这就是为什么当我们用十六进制表示时,我们可以连接十六进制值,而不是当它们是十进制(基数为 10)表示法时
来自 The wiki for hexadecimal