2

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.