2

I have the following issue. I have a file which used for storing array of some records (unknown structure). All that I know that all records separated with "." (dot). One of the "fields" of this record is a binary value.

So the structure is:

multiline_text <<binary_value>> multiline_text .

I can read file chunk-by-chunk (because it pretty large) and parse data to get actual data "<>" but it's not a binary value it's a string. I'm trying to convert it binary (to convert to term late) but i have no success.

I tried to use BIF list_to_binary (but it won't work because it is not a list) - it's already a binary. I tried to convert it to list of integers, fold them and convert and it's still is not working.

I suppose I'm missing something basic (I'm newbie in Erlang). Are there any advices?

2 Answers 2

2

If you get the binary you're interested in into an String in this format, for example:

S = "<< 1,2,3 >>".

then you can do something like this:

> {ok, T, _} = erl_scan:string(S ++ ".").
> {ok, Term} = erl_parse:parse_term(T). 
{ok,<<1,2,3>>}

and then you can use Term, that actually has the binary you just read as a string.

Sign up to request clarification or add additional context in comments.

3 Comments

Works for me. Thanks a lot! Is it hack or not?
First glance, this makes me nervous about potential injection attacks. Is that an unfounded suspicion in general when using parse_term, or are you making the assumption that the binary value is coming from a trusted source?
I think converting a string to a binary is not that problematic. It would be equally insecure as reading a buffer from a file.
1

Here is version without erl_parse. Just to study:

str2bin(Bin)->
Bin1 = string:strip(Bin, left, $<),
Bin2 = string:strip(Bin1, right, $>),
list_to_binary(lists:map(fun(Str) -> {Int, _Rest} = string:to_integer(string:strip(Str)), Int end, string:tokens(Bin2, ","))).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.