Last active
December 9, 2023 10:26
-
-
Save dkuku/1d9bbc7b9cf45262f6de8f3635c7b9ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
previous_fun = Inspect.Opts.default_inspect_fun() | |
hexdump = fn | |
value, opts when not is_binary(value) -> | |
# change base to hex - this way it will show binary numbers in instead of decimal | |
previous_fun.(value, %{opts | base: :hex}) | |
value, opts -> | |
{:ok, string_io} = StringIO.open(value) | |
printable_range = 0x20..0x7F | |
column_divider = " " | |
result = | |
string_io | |
|> IO.binstream(2) | |
|> Stream.take(opts.printable_limit) | |
|> Stream.chunk_every(8) | |
|> Stream.map( | |
&{ | |
# generates the text: AABB CCDD EEFF 1122 3344 5566 7788 9900 | |
Enum.map_join(&1, " ", fn two_chars -> Base.encode16(two_chars) end), | |
# generates the text: abc...def1234567 | |
for <<char::size(8) <- Enum.join(&1, "")>> do | |
if Enum.member?(printable_range, char), do: <<char>>, else: "." | |
end | |
} | |
) | |
|> Stream.with_index() | |
|> Enum.map_join("\n", fn {{chunk, original_text}, index} -> | |
[ | |
# generates the first column 00001 | |
String.pad_leading("#{index}", 6, "0"), | |
# last 0 and divider in the first column | |
"0", | |
column_divider, | |
# empty spaces for the last row when it's not full width | |
String.pad_trailing(chunk, 40, " "), | |
column_divider, | |
original_text | |
] | |
end) | |
StringIO.close(string_io) | |
"\n" <> result | |
end | |
Inspect.Opts.default_inspect_fun(hexdump) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this results in printing binaries with hexdump output: