slicing a binary

765 views
Skip to first unread message

Geoffrey Clements

unread,
Jul 4, 2014, 9:32:40 AM7/4/14
to elixir-l...@googlegroups.com
I've been using String.slice to remove the last couple of bytes from a binary. Something like:

String.slice(data, 0..-2)

I had a look at the library source and it looks like slice recurses a byte at a time to build the new character array. My problem is that the array may be 3 or 4 mega bytes long. Is it better to do:

<<data::[binary, size(expected)], rest::binary >>

to truncate the array? Where expected is the part of the array I want.





Eric Meadows-Jönsson

unread,
Jul 4, 2014, 9:34:48 AM7/4/14
to elixir-l...@googlegroups.com
String.slice slices a string, i.e. it slices a number of characters, a character may span multiple bytes. The bitsyntax doesn't know about strings or encodings so it slices a number of bytes.


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Eric Meadows-Jönsson

Alexei Sholik

unread,
Jul 4, 2014, 10:03:12 AM7/4/14
to elixir-l...@googlegroups.com
If `expected` is in bytes, the binary matching is the way to do it.

If it is in characters, there is no quick way to slice it other than traversing all characters from the beginning. (unless you can convert it to a list of characters in advance, but that's totally use-case-dependent).


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Best regards
Alexei Sholik

Geoffrey Clements

unread,
Jul 4, 2014, 12:27:29 PM7/4/14
to elixir-l...@googlegroups.com
Thanks for the help guys. Yeah, the binary syntax is what I want.

A little more looking turned up Kernel.binary_part(data, start, length) which is what I really need.


geoff
Reply all
Reply to author
Forward
0 new messages