Converting binary string to integer for a Ruby newbie

I want to convert a string of binary code ("011001") to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.

···

--
Posted via http://www.ruby-forum.com/.

Hi,

if you don't want to use the built-in methods, you'll have to loop over
the characters and sum the values of the digits.

The easiest way is to start from right and let an index count from 0 up.
This will give you the exponent of each power of 2:

num = '011001'
value = 0
'011001'.reverse.each_char.with_index do |dig, i|
  value += 2**i if dig == '1'
end
puts value

So for every digit "1", you add the corresponding value.

···

--
Posted via http://www.ruby-forum.com/.

curios:Why?

···

On 10/16/2012 8:16 PM, John Ringwalt wrote:

I want to convert a string of binary code ("011001") to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.

"011001".each_char.reverse_each.with_index.inject(0) {|v,(dig,i)| v +
(dig == '1' ? 2**i : 0 )} #=> 25

or use rubys cool features: Integer("0b" + "011001") #=> 25

···

--
Posted via http://www.ruby-forum.com/.

You can try this.

n = "0011001"

t = 0
n.each_char{|x| t = t*2+x.to_i}
p t

But if you are against using #to_i even like this, you could try this..

t = 0
n.each_char{|x| t = x=="1" ? t*2+1 : t*2}
p t

Or maybe,

t=0
n.each_char{|x| t=t*2+(x<=>"0")}
p t

Harry

···

On Wed, Oct 17, 2012 at 3:16 AM, John Ringwalt <lists@ruby-forum.com> wrote:

I want to convert a string of binary code ("011001") to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

John Ringwalt wrote in post #1080074:

I want to convert a string of binary code ("011001") to the integer
value WITHOUT using to_i or any other preset method. How can I do this?

Thanks for reading.

One of many solutions:

res = 0
str.each_char do |c|
  res *= 2
  res +=1 if c == "1"
end

···

--
Posted via http://www.ruby-forum.com/\.

Well that's totally helpful for someone trying to learn a new
language, or possibly programming. And totally readable for seasoned
devs. /sarcasm

+1 for Jan's answer.

-- Matma Rex

···

2012/10/16 Hans Mackowiak <lists@ruby-forum.com>:

"011001".each_char.reverse_each.with_index.inject(0) {|v,(dig,i)| v +
(dig == '1' ? 2**i : 0 )} #=> 25