LIFX header parsing returns invalid protocol number

I am trying to parse the LIFX headers according to their documentation .

Here is the code I have:

data = <<36, 0, 0, 52, 33, 235, 176, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0>> << size :: little-integer-size(16), origin :: little-integer-size(2), tagged :: size(1), addressable :: size(1), protocol :: little-integer-size(12), rest :: bitstring >> = data IO.puts protocol 

This tells me that protocol is 1027 , but the LIFX documentation says it should be 1024. I confirmed with LIFX RubyGem that this field value is 1024.

Why in Elixir do I see this value 1027 and not 1024?

+5
source share
1 answer

I am not an expert on this, but I have a theory that endianess does not work the way you expect when you take 12 bits instead of 16. This solution is just a numbers game, as I found this is an interesting problem. There might be a better solution; I haven't looked too far into the erlang implementation.

If we ignore all other data, then we have the following:

 data = <<0, 52>> # data is equal to 0000 0000 0011 0100 # oota pppp pppp pppp << origin :: little-integer-size(2), tagged :: size(1), addressable :: size(1), protocol :: little-integer-size(12) >> = data IO.puts protocol # 1027 IO.puts origin # 0 IO.puts tagged # 0 IO.puts addressable # 0 # doing little-endiain on 12 bits = 0100 0000 0011 # pppp pppp pppp 

Since this is a little endian, if we swap two bytes around, we get:

 data = <<52, 0>> # data is equal to 0011 0100 0000 0000 # oota pppp pppp pppp << origin :: integer-size(2), tagged :: size(1), addressable :: size(1), protocol :: integer-size(12) >> = data IO.puts protocol # 1024 IO.puts origin # 0 IO.puts tagged # 1 IO.puts addressable # 1 

So one of the solutions:

 data = <<0, 52>> << p1 :: integer-size(4), p2 :: integer-size(4), << origin :: size(2), tagged :: size(1), addressable :: size(1) >>, p3 :: integer-size(4) >> = data IO.inspect p1 # 0 IO.inspect p2 # 0 IO.inspect p3 # 4 << protocol :: size(12) >> = <<p3 :: size(4), p2 :: size(4), p1 :: size(4)>> IO.puts protocol # 1024 IO.puts origin # 0 IO.puts tagged # 1 IO.puts addressable # 1 
+3
source

All Articles