why
why

Reputation: 24851

How to pass a string to a function, which can create a binary later?

This is my function, when I call my_conv("2312144", 10, 10), it gives me "bad argument" error

my_conv(S, Start, End) ->
  Res = <<Start:8, End:8, S:1024>>.

Upvotes: 0

Views: 629

Answers (1)

Adam Lindberg
Adam Lindberg

Reputation: 16577

A string cannot be used inside a binary expression without conversion. You need to convert the string to a binary by using list_to_binary(S).

I would recommend the following expression:

my_conv(S, Start, End) ->
    list_to_binary(<<Start:8, End:8>>, S]).

(Note here that list_to_binary/1 actually accepts a deep IO list and not just a pure string).

If you intend to pad your binary to 1024 bytes (or 1040 including your newlines) you can do so afterwards:

my_conv(S, Start, End) ->
    pad(1040, list_to_binary(<<Start:8, End:8>>, S])).

pad(Width, Binary) ->
    case Width = byte_size(Binary) of
        N when N =< 0 -> Binary;
        N -> <<Binary/binary, 0:(N*8)>>
    end.

Upvotes: 5

Related Questions