How to Convert a Binary String to an Integer in Ruby?

In Ruby, you can use the Kernel#Integer method or the String#to_i method to convert a binary string to its integer equivalent. For example, you can do the following:

Convert Binary String With the 0b Radix Indicator

If the binary string is prefixed with "0b" (or "0B") binary radix prefix, then only for the String#to_i method you need to specify the numeric base of 2 because the Kernel#Integer method automatically converts strings with radix indicators. For example:

puts "0b11000000111001".to_i(2) #=> 12345

puts Integer("0b11000000111001") #=> 12345

If you don't specify the numeric base for the String#to_i method, then it would return 0:

puts "0b11000000111001".to_i #=> 0

This is because the String#to_i method only interprets leading characters as numbers in a string (which in this case is 0), and ignores characters beyond the end of a valid number.

Convert Binary String Without a Radix Indicator

If the binary string is not prefixed with "0b" (or "0B") binary radix prefix, then you must specify the numeric base of 2 to both methods (i.e. Kernel#Integer and String#to_i), for example, like so:

puts "11000000111001".to_i(2) #=> 12345

puts Integer("11000000111001", 2) #=> 12345

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.