[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Convert a n binary number to /n

Zangief Ief

8/14/2007 2:42:00 PM

Hi,

If my number is 1111, I would like to had 0000.
If my number is 1001, I would like to had 0110.
If my number is 0011, I would like to had 1100.

Of cours I know we can use XOR operator, but I would like to allow Ruby
to do it more simply, just by using a function as simple as possible. I
a sure this kind of function is yet setup in Ruby, but I don't know what
is his name.

Thank you for help.

Zang
--
Posted via http://www.ruby-....

4 Answers

Xavier Noria

8/14/2007 2:47:00 PM

0

On Aug 14, 2007, at 4:42 PM, Zangief Ief wrote:

> If my number is 1111, I would like to had 0000.
> If my number is 1001, I would like to had 0110.
> If my number is 0011, I would like to had 1100.
>
> Of cours I know we can use XOR operator, but I would like to allow
> Ruby
> to do it more simply, just by using a function as simple as
> possible. I
> a sure this kind of function is yet setup in Ruby, but I don't know
> what
> is his name.

A solution:

irb(main):003:0> "0011".tr("01", "10")
=> "1100"

-- fxn


Suraj Kurapati

8/14/2007 10:42:00 PM

0

Xavier Noria wrote:
> irb(main):003:0> "0011".tr("01", "10")
> => "1100"

Or, if you're working with integers (as opposed to strings), then you
can use the bitwise negation operator (~) and avoid the overhead of
string conversions altogether:

>> 0b1010
=> 10
>> ~0b1010
=> -11
>> ~(~0b1010)
=> 10
--
Posted via http://www.ruby-....

Zangief Ief

8/14/2007 10:56:00 PM

0

Thanks :)
--
Posted via http://www.ruby-....

Todd Burch

8/15/2007 1:11:00 AM

0

Zangief Ief wrote:
>If my number is 1111, I would like to had 0000.
>If my number is 1001, I would like to had 0110.
>If my number is 0011, I would like to had 1100.
> Thanks :)

sprintf("%04d", 1111- 1111) -> 0000
sprintf("%04d", 1111- 1011) -> 0100
sprintf("%04d", 1111- 1001) -> 0110
sprintf("%04d", 1111- 0011) -> 1102 (oops - it treats the second
value as octal)
sprintf("%04d", 1111- "0011".to_i) -> 1100

Todd
--
Posted via http://www.ruby-....