Skip to content

Instantly share code, notes, and snippets.

@emk
Created August 13, 2013 02:01
Show Gist options
  • Select an option

  • Save emk/6217182 to your computer and use it in GitHub Desktop.

Select an option

Save emk/6217182 to your computer and use it in GitHub Desktop.
Fun with Elixir bit bashing and weird Microsoft serialization formats
defmodule OcrMap.Parse do
use Bitwise, only_operators: true
def parse_7bit_encoded_int(rest) do
parse_7bit_encoded_int(rest, 0, 0)
end
def parse_7bit_encoded_int(<< 0::1, bits::7, rest::binary >>, shift, acc) do
{ (bits <<< shift) + acc, rest }
end
def parse_7bit_encoded_int(<< 1::1, bits::7, rest::binary >>, shift, acc) do
parse_7bit_encoded_int(rest, shift+7, (bits <<< shift) + acc)
end
end
defmodule OcrMap.ParseTest do
use ExUnit.Case
test "parse 7-bit encoded integers" do
{ i, rest } = OcrMap.Parse.parse_7bit_encoded_int(<< 0x1c, 0x62, 0x00 >>)
assert i == 28
assert rest == << 0x62, 0x00 >>
{ i, rest } = OcrMap.Parse.parse_7bit_encoded_int(<< 0xff, 0x01, 0x00 >>)
assert i == 255
assert rest == << 0x00 >>
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment