Convert a n binary number to /n

Z

Zangief Ief

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
 
X

Xavier Noria

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
 
S

Suraj Kurapati

Xavier said:
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:
=> 10
 
T

Todd Burch

Zangief said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top