snacktime
8/13/2006 6:24:00 AM
If anyone has any input on how to write this better or a better way to
implement it let me know. In any case here is a class for setting
odd/even/space parity on strings.
class StringParity
def initialize
even_bits = "\0"
odd_bits = "\200"
codes = ""
ascii = []
@even_parity = []
@odd_parity = []
@space_parity = []
8.times do
even_bits << odd_bits
odd_bits = even_bits.clone
odd_bits.tr!("\0\200","\200\0")
end
(0..255).collect {|i| ascii << i}
codes = ascii.pack('C*')
(0..127).collect { |i| @space_parity[i + 128] = codes[i] }
@even_parity = (0..codes.length-1).collect { |i| codes[i] ^ even_bits[i] }
@odd_parity = (0..codes.length-1).collect { |i| codes[i] ^ odd_bits[i] }
end
def setEvenParity(str)
new = []
str.each_byte {|b| new << @even_parity[b]}
new.pack("C*")
end
def setOddParity(str)
new = []
str.each_byte {|b| new << @odd_parity[b]}
new.pack("C*")
end
def setSpaceParity(str)
new = []
str = str.unpack("C*")
str.collect {|b| new << (@space_parity[b] || b)}
new.pack("C*")
end
end
s = StringParity.new
str = "testing12345678910()*&^%@!~"
str = s.setEvenParity(str)
print "#{str}\n"
str = s.setSpaceParity(str)
print "#{str}\n"
str = s.setOddParity(str)
print "#{str}\n"
str = s.setSpaceParity(str)
print "#{str}\n"