Reputation: 24851
A = <<"hello">>.
B = <<A:80/binary, 100:8>>.
It gives me:
** exception error: bad argument
and <<"hello">>.
works, but:
A = "hello".
<<A>>.
can not work.
Upvotes: 2
Views: 154
Reputation: 26121
A
doesn't have size 80 bytes which obviously doesn't match A:80/binary
in first case.
1> A = <<"hello">>.
<<"hello">>
2> B = <<A/binary, 100:8>>.
<<"hellod">>
3> Pad = 80 - size(A), C = <<A/binary, 0:Pad/unit:8, 100:8>>.
<<104,101,108,108,111,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,...>>
<<"hello">>
is syntactic sugar for <<$h,$e,$l,$l,$o>>
. Bit syntax expression assumes 8/integer,unsigned,big,unit:1
type specification by default. A
is not integer so <<A>>
raises badarg
exception in second case.
Upvotes: 4
Reputation: 18869
The value <<"Hello">> works but only because "Hello" is a string literal. When you write,
A = "Hello",
you are creating a String object, which is really a list of unicode codepoints. Now, when you declare,
<<A>>
then A
is assumed to be an integer because the is the default. Naturally something is wrong when you try to inject a list/string for an integer, which is the reason for the badarg.
The solution is two-fold:
list_to_binary(A)
will convert the list to a binary. Now you have the equivalent of <<A/binary>>
and you can manipulate it:
L = byte_size(A),
<<L:32/integer, A/binary>>
Upvotes: 0