Open In App

How to convert a number to Binary in Ruby?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Ruby, converting a number to binary involves utilizing built-in methods or implementing custom algorithms. Binary representation is a base-2 numeral system, where each digit can be either 0 or 1.

There are many ways to convert a number to binary in Ruby like:

  • Using String Interpolation with %b Format
  • Using Integer#to_s with Base Argument
  • Using Bitwise Operators

Using String Interpolation with %b Format

Ruby has a string formatting feature that is used with % together with the format specifier, %b for binary representation. It simply changes the number into its binary form in a string.

Syntax:

“%b” % number

Example:

Ruby
number = 42
binary_string = "%b" % number
puts binary_string

Output
101010

Using Integer#to_s with Base Argument

Like in previous method, integer class can also convert an integer into a string which can be optionally specified for use as the base. By specifying base 2, you will obtain your binary representation.

Syntax:

binary_string = number.to_s(2)

Example:

Ruby
number = 42
binary_string = number.to_s(2)
puts binary_string  

Output
101010

Using Bitwise Operators

There are other ways like shifting through bitwise operations that you can manually convert numbers for them to become binary and all this has a little bit more control but also needs more code.

Syntax:

def to_binary(number)
binary_string = ""
until number == 0
bit = number & 1
binary_string.prepend(bit.to_s)
number >>= 1
end
binary_string
end

Example:

Ruby
def to_binary(number)
  binary_string = ""
  until number == 0
    bit = number & 1
    binary_string.prepend(bit.to_s)
    number >>= 1
  end
  binary_string
end

number = 42
binary_string = to_binary(number)
puts binary_string  

Output
101010

CONCLUSION:

Ruby allows different approaches for converting numbers into their binary forms; these include employing typical techniques that save time and space as well as making tailored solutions for transparency and customization. To choose whether it would be better to write cleaner or faster code purely based on how readable, efficient or controllable you want it.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads