【问题标题】:String to binary, difference between constant and variable conversion字符串到二进制,常量和变量转换的区别
【发布时间】:2014-03-10 13:58:29
【问题描述】:

谁能解释一下为什么第二个语句给出了badarg

谢谢

42> <<"hello">>.
<<"hello">>
43> Content = "hello".
"hello"
44> <<Content>>.
** exception error: bad argument

【问题讨论】:

    标签: string binary erlang type-conversion


    【解决方案1】:

    &lt;&lt;"hello"&gt;&gt; 只是一种特殊语法,用于创建包含字符串文字中的字节的二进制文件——它是&lt;&lt;$h, $e, $l, $l, $o&gt;&gt; 的语法糖,它看起来像一个字符串(即字符列表)的事实是只是巧合。

    如果字符串在变量中,不能直接插入二进制;你需要明确地转换它:

    ContentBinary = list_to_binary(Content),
    

    【讨论】:

      【解决方案2】:

      当您在控制台或程序中键入 > 时,它是一种快捷方式,表示将列表 "hello" 转换为二进制。然后控制台使用漂亮的打印格式来显示它。

      当您将 Content 定义为列表“hello”时,语法快捷方式不再可用,并且 erlang 正在寻找有效类型(Type= integer | float | binary | bytes | bitstring | bits | utf8 | utf16 | utf32 )并找到一个列表,这就是为什么你会得到这个错误的参数例外。

      以下条目正确:

      7> V1 = <<"hello">>.         
      <<"hello">>
      8> V2 = "hello".             
      "hello"
      9> V1 = list_to_binary(V2).  
      <<"hello">>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-22
        • 2014-06-09
        • 1970-01-01
        • 2013-02-11
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多