如何在 elixir 中将二进制转换为 base10(十进制)整数

How to convert a binary to a base10 (decimal) integer in elixir

我希望能够将 elixir 字符串(二进制)转换为 base10 整数。

我已经能够通过以下方法做到这一点...

<<104, 101, 108, 108, 111>> # equal to string "hello"
|> Base.encode16()
|> Integer.parse(16)

{448378203247, ""}

以上内容满足了我的要求,但感觉有点像 hack。我想...

由于 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) 这就是为什么当我们用十六进制表示时,我们可以只连接十六进制值,而不是当它们是十进制(base-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.

在 Elixir 中将二进制(基数 2)数转换为十进制数(基数 10):

Integer.parse("1111111", 2) |> elem(0) 给出 127

:erlang.binary_to_integer(<<"1111111">>, 2) 给出 127

虽然这没有回答上面 OP 的示例,但它回答了他的标题。

Also:Elixir 在其交互式控制台 (IEx) 中为我们提供了将二进制、八进制和十六进制数转换为十进制数的快捷方式。如果是二进制,请在数字前加上 0b,如果是八进制,请在前 0o,如果是十六进制,请在前 0x,然后输出十进制版本。

所以 0b1111111 在 IEx 中给出 127。

在 Elixir 中将十进制数转换为二进制数:

Integer.to_string(127, 2) 给出“1111111”