defmodule PokeLib.Utils do
require Bitwise
@doc "Gets a part at offset of size."
def get_part(data, offset, size, parser \\ nil) do
<<_ :: binary-size(offset), fetched :: binary-size(size), _rest :: binary>> = data
if parser, do: parser.(fetched), else: fetched
end
@doc "Decodes two bytes into an integer."
def two_bytes_to_integer(<>) do
a = a |> :binary.encode_unsigned |> Base.encode16
b = b |> :binary.encode_unsigned |> Base.encode16
{res, _} = Integer.parse(a <> b, 16)
res
end
def three_bytes_to_integer(<>) do
a = a |> :binary.encode_unsigned |> Base.encode16
b = b |> :binary.encode_unsigned |> Base.encode16
c = c |> :binary.encode_unsigned |> Base.encode16
{res, _} = (a <> b <> c) |> Integer.parse(16)
res
end
@doc "Encodes an integer into two bytes."
def integer_to_two_bytes(int) do
b = Bitwise.&&&(int, 0xFF)
a = Bitwise.>>>(int, 8) |> Bitwise.&&&(0xFF)
<>
end
@doc "Decodes an integer into three bytes."
def integer_to_three_bytes(int) do
a = Bitwise.>>>(int, 16) |> Bitwise.&&&(0xFF)
b = Bitwise.>>>(int, 8) |> Bitwise.&&&(0xFF)
c = Bitwise.&&&(int, 0xFF)
<>
end
@doc "Pads up to three digits."
def get_four_bits(data) do
case Integer.digits(data, 2) do
[_, _, _, _] = res -> res
[a, b, c] -> [0, a, b, c]
[a, b] -> [0, 0, a, b]
[a] -> [0, 0, 0, a]
end
end
end