﻿ How to Convert a String or Integer to Binary in Ruby - ITCodar

# How to Convert a String or Integer to Binary in Ruby

## Converting Integers to Binary in Ruby

I am not fond of this approach since I'm sure there's an even more clever and/or compact, Ruby-esque way of accomplishing it. But using your method of loading binary digits into an array, and then joining, what you have can be done in a little more straight-forward fashion:

``def to_binary(n)  return "0" if n == 0  r = []  32.times do    if (n & (1 << 31)) != 0      r << 1    else      (r << 0) if r.size > 0    end    n <<= 1  end  r.joinend``

Or, using @500_error's suggestion:

``def to_binary(n)  if n >= 0    n.to_s(2)  else    31.downto(0).map { |b| n[b] }.join  endend``

The asymmetry to deal with negative versus non-negative is a little annoying, though. You could do something like:

``def to_binary(n)  31.downto(0).map { |b| n[b] }.join.sub(/^0*/, "")end``

## How to Convert String to Binary in Ruby

There is no notion of "decimal number" or "binary number" in Ruby objects. All there is is numbers (actually all numbers are binary at the low level, and necessary not at a higher level, but that is irrelevant to Ruby objects). "Decimal" or "binary" are only some ways to represent numbers. Therefore, you cannot convert something into a "binary number". All you can do is to convert it to a number.

## Ruby Convert integer to binary to integer array of set bits

This would work:

``i = 98(0...i.bit_length).map { |n| i[n] << n }.reject(&:zero?)#=> [2, 32, 64]``
• `Fixnum#bit_length` returns the position of the highest "1" bit
• `Fixnum#[n]` returns the integer's nth bit, i.e. `0` or `1`
• `Fixnum#<<` shifts the bit to the left. `1 << n` is equivalent to 2n

Step by step:

``(0...i.bit_length).map { |n| i[n] }#=> [0, 1, 0, 0, 0, 1, 1](0...i.bit_length).map { |n| i[n] << n }#=> [0, 2, 0, 0, 0, 32, 64](0...i.bit_length).map { |n| i[n] << n }.reject(&:zero?)#=> [2, 32, 64]``

You might want to `reverse` the result.

## Create a decimal to binary converter using Ruby?

Float, as ruby does it, doesn't have a binary representation. If you want to convert between bases you can use to_s by passing the base in as a paramter.

``21.to_s(2) #-> 10101``

The appropriate way to do this is to use Kernel's `sprintf` formatting:

``'%03b' % 1 # => "001"'%03b' % 2 # => "010"'%03b' % 7 # => "111"'%08b' % 1 # => "00000001"'%08b' % 2 # => "00000010"'%08b' % 7 # => "00000111"``

But wait, there's more!:

``'%0*b' % [3, 1] # => "001"'%0*b' % [3, 2] # => "010"'%0*b' % [3, 7] # => "111"'%0*b' % [8, 1] # => "00000001"'%0*b' % [8, 2] # => "00000010"'%0*b' % [8, 7] # => "00000111"``

So defining a method to extend Fixnum or Integer is easy and cleanly done:

``class Integer  def to_bin(width)    '%0*b' % [width, self]  endend1.to_bin(8) # => "00000001"0x55.to_bin(8) # => "01010101"0xaaa.to_bin(16) # => "0000101010101010"``

## Convert binary string to hexadecimal in Ruby

You can convert it to an integer first, hinting that the string is binary (`to_i(2)`), then to hexadecimal (`to_s(16)`

``"1010".to_i(2).to_s(16) # => 'a'``

If you need it in uppercase, you can call `upcase` on the resulting string.

## Ruby convert int to bin and vice versa

You can use `sprintf`:

``sprintf("%08b", 127) #=> "01111111"#         ^^^#         |||#         ||+- "b" = format argument as binary number#         |+-- "8" = number of digits#         +--- "0" = pad with 0``