wuntee
wuntee

Reputation: 12490

Ruby: Flip characters bits

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.

Upvotes: 2

Views: 3600

Answers (2)

Mladen Jablanović
Mladen Jablanović

Reputation: 44090

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"

Upvotes: 2

Chowlett
Chowlett

Reputation: 46677

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"

Upvotes: 7

Related Questions