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.
How can I perform bitwise operations on strings in ruby? I would like to
Share
If you are always going to operate on 4-byte strings,
String#unpackwith 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 thatunpackalways returns an array, thus the need to take index 0.If it’s not always four bytes, you can call
String#bytesto get the bytes of the string, and then you can useEnumerable#injectto accumulate the bytes into a number.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.