Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a bit to the end of a bit string?

Tags:

elixir

I'm looking to construct a bit string bit by bit, and am wondering how to do so.

I was expecting the syntax to be similar to concatenating two bytes like so:

iex(1)> <<1>> <> <<1>>
<<1, 1>>

So I tried:

iex(2) <<1::1>> <> <<1::1>>
** (ArgumentError) argument error

Is this possible? Thanks in advance.

like image 763
djdrzzy Avatar asked Jan 10 '16 21:01

djdrzzy


People also ask

How do I concatenate a bit in Python?

By shifting the first byte by 4 bits to the left (first<<4) you'll add 4 trailing zero bits. Second part (second>>4) will shift out to the right 4 LSB bits of your second byte to discard them, so only the 4 MSB bits will remain, then you can just bitwise OR both partial results ( | in python) to combine them.

How many bits are in a bit string?

Bit String Segments By default a Bit String segment represents 8 bits, also known as 1 byte. You can also specify a bit size using either short hand or long form.

How long is a bit string?

A bit string (also called a word) is a sequence of bits of some set length. Usually the length is some small power of 2: 4, 8, 16, 32, 64). A byte is a bit string of length 8. There are 256 different bytes.


1 Answers

I'm not exactly sure if it's a bug or not, but let's explore what's going on and worry about that later.

What is <>? It turns out it's just a macro defined in Kernel.<>/2. What can we do with macros to understand them better? Expand them!

quote(do: <<1::1>> <> <<1::1>>) 
|> Macro.expand(__ENV__) 
|> Macro.to_string
#=> "<<(<<1::1>>::binary), (<<1::1>>::binary)>>"

We can see that <> desugars to the normal binary syntax. Unfortunately for us it assumes it's arguments are binaries! We have bitstrings - hence the error. How to fix it? We can use the regular binary/bitstring syntax directly:

<< <<1::1>>::bitstring, <<1::1>>::bitstring >>
#=> <<3::size(2)>>

Which works as expected.

EDIT: I followed up on this. This behaviour is expected. <> operator is designed to work on binaries and not bitstrings. The error is rather unpleasant, but it's coming deep from within Erlang.

like image 92
michalmuskala Avatar answered Sep 24 '22 22:09

michalmuskala