Papillon6814
How to convert decimal value to binary value?
I want to convert “3” to “11”, and then “11” to “00000011” in elixir.
But I don’t know any ways to do it.
Help me!
Marked As Solved
benwilson512
When I don’t know how to do something in Elixir, the first place I look is the module that has code related to the kind of data I’m trying to deal with. In this case, you’re trying to turn a String into an integer, and then represent that integer in a particular base.
Turning a string into an integer can be accomplished with a function found in this module: https://hexdocs.pm/elixir/String.html
And turning an integer into the digits of a specific base can be found with a function in this module: https://hexdocs.pm/elixir/Integer.html
Give it a shot! We’ll be here if you have further questions.
Also Liked
ericgray
You can break this down into 3 easy steps using the modules that @benwilson512 recommends.
-
Convert string to integer
String.to_integer("3") -
Get binary value of integer
Integer.to_string(3, 2) -
Pad binary string with zeros
String.pad_leading("11", 8, "0")
You can write the code with guard clauses to handle strings or integers.
def decimal_to_binary(decimal) when is_binary(decimal) do
decimal
|> String.to_integer()
|> decimal_to_binary()
end
def decimal_to_binary(decimal) when is_integer(decimal) do
decimal
|> Integer.to_string(2)
|> String.pad_leading(8, "0")
end
hauleth
Oh yeah, it should be "~8.2.0B"
hauleth
Just format it properly - List.to_string(:io_lib.format("~8.2B", [3]))







