[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: how to translate base 10 number into base 2 number

Jacob, Raymond A Jr

1/15/2007 11:54:00 AM

Is there a way to pad the result with leading zeros
i.e. 4.to_s(2)
"100"
What I am trying to do is sort ip addresses
i.e. "192.61.14.30"
When I try to convert "192.61.14.30"
a ="192.61.14.30".split(/\./)
b = a.collect{|i| i.to_i.to_s(2) }
p b
["11000000","111101", "1110", "11110"]
p b.join
"11000000111101111011110".to_i

How would you pad the results of .to_s(2) to come up with a byte?

Thank you,
raymond


-----Original Message-----
From: khaines@enigo.com [mailto:khaines@enigo.com]
Sent: Sunday, January 14, 2007 12:07
To: ruby-talk ML
Subject: Re: how to translate base 10 number into base 2 number

On Mon, 15 Jan 2007, chen li wrote:

> Hi all,
>
> I want to write a method to tranlate base 10 number into base 2
> number. I want to call the method within itself. But it doesn't work.
> What is the right way to do something like this?

This doesn't answer your question, but in case you were not aware, Ruby
will do this conversion for you:


a = 125
puts a.to_s(2)
1111101


Kirk Haines


2 Answers

Robert Klemme

1/15/2007 11:59:00 AM

0

On 15.01.2007 12:54, Jacob, Raymond A Jr wrote:
> Is there a way to pad the result with leading zeros
> i.e. 4.to_s(2)
> "100"

irb(main):004:0> "%08b" % 4
=> "00000100"
irb(main):005:0> sprintf "%08b", 4
=> "00000100"

robert

Carlos

1/15/2007 12:03:00 PM

0

Jacob, Raymond A Jr wrote:
(speaking of strings...)

> Is there a way to pad the result with leading zeros

$ ri String#rjust

----------------------------------------------------------- String#rjust
str.rjust(integer, padstr=' ') => new_str
------------------------------------------------------------------------
If _integer_ is greater than the length of _str_, returns a new
+String+ of length _integer_ with _str_ right justified and padded
with _padstr_; otherwise, returns _str_.

"hello".rjust(4) #=> "hello"
"hello".rjust(20) #=> " hello"
"hello".rjust(20, '1234') #=> "123412341234123hello"

HTH
--