Convert a n binary number to /n

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-forum.com/.

A solution:

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

-- fxn

···

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.

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-forum.com/.

Thanks :slight_smile:

···

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

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 :slight_smile:

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-forum.com/.