From: Robert Klemme Date: 2008-01-28T19:09:14+09:00 Subject: Re: Logical Operations on Strings 2008/1/28, Michael W. Ryder <_mwryder@worldnet.att.net>: > Is there a bitwise and for strings that I am missing? I tried the > documentation and Google with no luck. I coded a simple method to > handle this, it obviously needs more error checking, but don't want to > reinvent the wheel if not necessary. > > def AND(s, m) > t = s.dup > for i in 0...(s.size <= m.size ? s.size : m.size) > t[i] = (s[i] & m[i]).chr > end > return t > end I believe this implementation is flawed because it returns a string that is too long if self.size > m.size. This is what I'd probably do class String def &(s) t = "" [size, s.size].min.times do |i| t << (self[i] & s[i]) end t end def |(s) t = "" [size, s.size].max.times do |i| t << ((self[i] || 0) | (s[i] || 0)) end t end end Now you can do irb(main):020:0> 0.chr | "a" => "a" irb(main):021:0> 0.chr | "abc" => "abc" irb(main):022:0> 0.chr & "abc" => "\000" irb(main):023:0> a="s" => "s" irb(main):024:0> a|="123" => "s23" irb(main):025:0> a&="\012" => "\002" > On a related note, is there any way to create a string from a hex number > other than separating each two digits and using .chr to convert them to > a number and adding them to the string? If I have a string such as > 0x7FFFFFFFFFFF I have to use something like str1 = 0x7F.chr followed by > 5 str1 << 0xFF.chr which seems to be unnecessarily clumsy. I am not sure which direction you mean (there is no such thing as a "hex number" in Ruby, a number is a number, hex is just one representation - internally they are most likely stored binary). Does this help? irb(main):001:0> 123.to_s 16 => "7b" irb(main):002:0> "%04x" % 123 => "007b" irb(main):003:0> "7b".to_i 16 => 123 Kind regards robert -- use.inject do |as, often| as.you_can - without end