aboutsummaryrefslogtreecommitdiff
path: root/semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs
diff options
context:
space:
mode:
authorAnhgelus Morhtuuzh <william@herges.fr>2025-09-13 00:53:47 +0200
committerAnhgelus Morhtuuzh <william@herges.fr>2025-09-13 00:53:47 +0200
commitcac7f3e868e98281f9f2b841101b09f02cf664fd (patch)
tree7e83f551f4caa7f928742becdbc1dede5ec1b9fe /semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs
parent11d5e7431489b8b40cf479a7f88c171d6fbf77a7 (diff)
Ajout du scripts bin_to_hex
Diffstat (limited to 'semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs')
-rw-r--r--semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs38
1 files changed, 38 insertions, 0 deletions
diff --git a/semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs b/semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs
new file mode 100644
index 0000000..8d6e629
--- /dev/null
+++ b/semestre 3/architecture des ordinateurs/scripts/bin_to_hex.exs
@@ -0,0 +1,38 @@
+defmodule Conv do
+ def bin_to_hex(b) do
+ bin_to_hex_rec(b, [])
+ end
+
+ defp bin_to_hex_rec(before, aft) when before != "" do
+ {b, a} = String.split_at(before, -4)
+ s = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
+ bin_to_hex_rec(b, [Enum.at(s, bin_to_dec(a)) | aft])
+ end
+
+ defp bin_to_hex_rec("", aft) do
+ aft
+ end
+
+ def bin_to_dec(b) do
+ bin_to_dec_rec(b, 0, 0)
+ end
+
+ defp bin_to_dec_rec(before, aft, i) when before != "" do
+ {b, a} = String.split_at(before, -1)
+ bin_to_dec_rec(b, case a do
+ "0" -> aft
+ "1" -> aft + Integer.pow(2, i)
+ end, i + 1)
+ end
+
+ defp bin_to_dec_rec("", aft, _i) do
+ aft
+ end
+end
+
+Conv.bin_to_hex("1111")
+|> IO.puts() # must print f
+
+Conv.bin_to_hex("11101011")
+|> IO.puts() # must print EB
+