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

标签 encoding int erlang elixir base

我希望能够将 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/

    相关文章:

    erlang - erlang集群中的多个nodedown消息

    ssl - 无法连接到 SSL LDAP 服务器

    python - 将 'bytes' 对象转换为字符串

    javascript - 用Java对Http请求进行编码和解码

    encoding - H264帧间预测如何填充预测 block 旧位置?

    完成循环的 c int 比较

    java - 使用 URL.openStream() 下载的 HTML 内容始终包含无效字符

    c - C 中 short int 的最小值/最大值

    ios - 将最大 int 值(不是字符数)设置为 UITextField

    types - Erlang 的打字机推导出奇怪的字符串类型