我希望能够将 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
二进制其小数(基数 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
Hexadecimal numerals are widely used by computer system designers and programmers, as they provide a more human-friendly representation of binary-coded values. Each hexadecimal digit represents four binary digits, also known as a nibble, which is half a byte. For example, a single byte can have values ranging from 0000 0000 to 1111 1111 in binary form, which can be more conveniently represented as 00 to FF in hexadecimal.
关于encoding - 如何在 elixir 中将二进制转换为 base10(十进制)整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441543/