Hi,
Anyone know how to parse a bitstring?
I have values like this : <<170, 192, 65, 0, 100, 0, 61, 86, 56, 171>> coming in from a sensor.
I need to get 65 ad 100 out to of that without changing them to another number. Anyone have an idea as to how to do that?
Thanks
1 Like
kip
February 24, 2019, 4:10pm
2
Something like this:
iex> x = <<170, 192, 65, 0, 100, 0, 61, 86, 56, 171>>
iex> << _ :: bytes-4, onehundred :: bytes-1, _ :: bytes-1, sixtyone :: bytes-1, _rest :: binary >> = x
<<170, 192, 65, 0, 100, 0, 61, 86, 56, 171>>
iex> onehundred
"d"
iex> sixtyone
"="
This assumes you want the fields as binaries. If you want them as integers:
iex> << _ :: bytes-4, onehundred :: size(8), _ :: bytes-1, sixtyone :: size(8), _rest :: binary >> = x
<<170, 192, 65, 0, 100, 0, 61, 86, 56, 171>>
iex> sixtyone
61
iex> onehundred
100
2 Likes
I’m sorry If I wasn’t clear.
When I said I wanted to get 65 I mean literally a “65” from that bitstring.
As in I want a list of all of the number values.
Ex:
a = <<170, 192, 65, 0, 100, 0, 61, 86, 56, 171>>
b = some_function(a)
b == [170, 192, 65, 0, 100, 0, 61, 86, 56, 171]
kip
February 24, 2019, 4:16pm
4
Here you go:
iex> :binary.bin_to_list x
[170, 192, 65, 0, 100, 0, 61, 86, 56, 171]
4 Likes
Is this from the Erlang library?
kip
February 24, 2019, 4:17pm
6
Yes, it is. Everything in Erlang is available in Elixir.
3 Likes