# 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!

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.

9 Likes

As an alternative to @benwilson512 's method, sometimes I just fire up an iex and `h SomeModule.<tab>` or something alike, and search for the function that could work. If none is found, I’ll try `h Kernel.<tab>`.

For example, for the last step in your problem, I’d `h String.<tab>`, and fortunately, I can find `pad_leading/2` and `pad_leading/3` in the function list, then I `h String.pad_leading` to view their documentation.

1 Like

Just format it properly - `List.to_string(:io_lib.format("~8.2B", ))`

5 Likes

You can break this down into 3 easy steps using the modules that @benwilson512 recommends.

1. Convert string to integer `String.to_integer("3")`

2. Get binary value of integer `Integer.to_string(3, 2)`

3. 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)
end
``````
5 Likes

Still IMHO overcomplicated:

``````def decimal_to_binary(str) when is_binary(str) do
decimal
|> String.to_integer()
|> decimal_to_binary()
end

def decimal_to_binary(num) when is_integer(num),
do: List.to_string(:io_lib.format("~8.2B", [num]))
``````
1 Like

This gives leading whitespaces, not zeroes. Do you know if there’s a modifier to make it do zeroes?

3 Likes

Oh yeah, it should be `"~8.2.0B"`

6 Likes

Thank you!
All suggestions helped me!

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))