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

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

is his name.
A solution:

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

– fxn

Xavier N. 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

Thanks :slight_smile:

Zangief I. 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