用ruby对字符串进行按位运算 [英] bitwise operations on strings with ruby

查看:51
本文介绍了用ruby对字符串进行按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ruby中对字符串执行按位运算?我想做一个 bitwise& 一个4字节长的十六进制的4字节字符串,例如("abcd"& 0xDA2DFFD3).我无法获取字符串的字节值.感谢您的帮助.

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.

推荐答案

如果您始终要对4字节字符串进行操作,请

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"

如果不是总是四个字节,则可以调用 String#bytes 来获取字符串的字节,然后可以使用 Enumerable#inject 来累积字节变成数字.

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"

这是安全的",只要您使用ASCII字符串即可.如果您开始使用多字节字符串,则将获得奇数"结果.

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.

这篇关于用ruby对字符串进行按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆