2

I am simply trying to flip the bits of a character. I can get it into a binary form, but when xoring that data with 0xff it seems to not be giving me what I want.

bin = "a".unpack("b*")[0].to_i # Will give me the binary value        (10000110)
flip = bin ^ 0xff              # this will give me 9999889, expecting (01111001)

Finally, I want to re-pack it as a "character"...

Any help would be appreciated.

2 Answers 2

7

You need to tell Ruby that the unpacked string is binary:

bin = "a".unpack("b*")[0].to_i(2) # => 134
flip = bin ^ 0xff # => 121
flip.to_s(2) # => "1111001"
[flip.to_s(2)].pack("b*") # => "O"
2

Couple of things:

You probably want unpack('B*'), not b* as b* gives you LSB first.

You probably don't need binary at all ("binary" is just a representation of a number, it doesn't need to be "a binary number" in order to XOR it). So you can do simply:

number = "a".unpack('C*')[0]
flip = number ^ 0xff
new_number = [flip].pack('C*')

or, even:

number = "a".ord
flip = number ^ 0xff
new_number = flip.chr

Oh, and the result should not be "O"

2
  • the second example doesnt seem to work on 1.9, but the first one is much easier to understand
    – wuntee
    Nov 22, 2011 at 19:27
  • Which version you have tried it with? Works in 1.9.1 and 1.9.2 over here. Also: ideone.com/y74Ov Nov 22, 2011 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.