From 3caabd336d1034bbce76a153ca412d899439afed Mon Sep 17 00:00:00 2001 From: James Harton Date: Tue, 14 Jan 2020 19:54:36 +1300 Subject: [PATCH] Add some handy-dandy number formatting. --- lib/wafer/format.ex | 67 ++++++++++++++++++++++++++++++++++++++++++++ test/format_test.exs | 5 ++++ 2 files changed, 72 insertions(+) create mode 100644 lib/wafer/format.ex create mode 100644 test/format_test.exs diff --git a/lib/wafer/format.ex b/lib/wafer/format.ex new file mode 100644 index 0000000..f037657 --- /dev/null +++ b/lib/wafer/format.ex @@ -0,0 +1,67 @@ +defmodule Wafer.Format do + use Bitwise + + @moduledoc """ + Handy functions for formatting bytes, especially for debugging. + """ + + @doc """ + Convert the provided value into it's 0-padded byte-oriented string + representation. + + ## Examples + + iex> to_hex(0x1234) + "0x1234" + + iex> to_hex(<<0xF0, 0x0F>>) + "0xF00F" + """ + @spec to_hex(integer | binary) :: String.t() + def to_hex(value) when is_integer(value) do + value + |> :binary.encode_unsigned() + |> to_hex() + end + + def to_hex(value) when is_binary(value) do + bits = + value + |> :binary.bin_to_list() + |> Stream.map(&Integer.to_string(&1, 16)) + |> Stream.map(&String.pad_leading(&1, 2, "0")) + |> Enum.join("") + + "0x" <> bits + end + + @doc """ + Convert the provided value into it's 0-padded byte-oriented string + representation. + + ## Examples + + iex> to_bin(0x1234) + "0b00010010_00110100" + + iex> to_bin(<<0xF0, 0x0F>>) + "0b11110000_00001111" + """ + @spec to_bin(integer | binary) :: String.t() + def to_bin(value) when is_integer(value) do + value + |> :binary.encode_unsigned() + |> to_bin() + end + + def to_bin(value) when is_binary(value) do + bits = + value + |> :binary.bin_to_list() + |> Stream.map(&Integer.to_string(&1, 2)) + |> Stream.map(&String.pad_leading(&1, 8, "0")) + |> Enum.join("_") + + "0b" <> bits + end +end diff --git a/test/format_test.exs b/test/format_test.exs new file mode 100644 index 0000000..c9394b5 --- /dev/null +++ b/test/format_test.exs @@ -0,0 +1,5 @@ +defmodule WaferFormatTest do + use ExUnit.Case, async: true + import Wafer.Format + doctest Wafer.Format +end