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: String — Elixir v1.20.2
And turning an integer into the digits of a specific base can be found with a function in this module: Integer — Elixir v1.20.2
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
hauleth
Last Post!
slouchpie
None of the “written code” solutions here work for numbers greater than 255.
I think this solution works for all (positive) numbers:
def decimal_to_binary(str) when is_binary(str) do
str
|> String.to_integer()
|> decimal_to_binary()
end
def decimal_to_binary(num) when is_integer(num) do
binary_string = :erlang.integer_to_binary(num, 2)
binary_string_length = String.length(binary_string)
desired_string_length = binary_string_length + (8 - rem(binary_string_length, 8))
String.pad_leading(binary_string, desired_string_length, "0")
end
It could probably be neater but at least it works for numbers larger than 255.
Any improvements are very welcome!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









