views:

181

answers:

1

How can I perform bitwise operations on strings in ruby? I would like to do bitwise & a 4-byte string with a 4-byte long hex such as ("abcd" & 0xDA2DFFD3). I cannot get the byte values of the string. Thanks for your help.

+2  A: 

If you are always going to operate on 4-byte strings, String#unpack with an argument of 'V' will treat four bytes as an unsigned long in little-endian byte order. Using 'N' will force network byte order, and using 'L' will use native order. Note that unpack always returns an array, thus the need to take index 0.

>> '0x%X' % ('abcd'.unpack('V')[0] & 0xDA2DFFD3)
=> "0x40216241"

If it's not always four bytes, you can call String#bytes to get the bytes of the string, and then you can use Enumerable#inject to accumulate the bytes into a number.

>> "abcd".bytes.inject {|x, y| (x << 8) | y}
=> 1633837924
>> "abcd".bytes.inject {|x, y| (x << 8) | y}.to_s(16)
=> "61626364"
>> "abcd".bytes.inject {|x, y| (x << 8) | y} & 0xDA2DFFD3
=> 1075864384
>> "0x%X" % ("abcd".bytes.inject {|x, y| (x << 8) | y} & 0xDA2DFFD3)
=> "0x40206340"

This is "safe" as long as you're using ASCII strings. If you start using multi-byte strings, you're going to get "odd" results.

Mark Rushakoff
exactly what I needed. Thanks.
artsince