string parity module

Discussion in 'Ruby' started by snacktime, Aug 12, 2006.

  1. snacktime

    snacktime Guest

    Anyone know of an existing module for settings odd/even/space parity on strings?
     
    snacktime, Aug 12, 2006
    #1
    1. Advertising

  2. snacktime

    snacktime Guest

    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 }
    @even_parity = (0..codes.length-1).collect { |i| codes ^ even_bits }
    @odd_parity = (0..codes.length-1).collect { |i| codes ^ odd_bits }
    end

    def setEvenParity(str)
    new = []
    str.each_byte {|b| new << @even_parity}
    new.pack("C*")
    end

    def setOddParity(str)
    new = []
    str.each_byte {|b| new << @odd_parity}
    new.pack("C*")
    end

    def setSpaceParity(str)
    new = []
    str = str.unpack("C*")
    str.collect {|b| new << (@space_parity || 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"
     
    snacktime, Aug 13, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ed

    Parity Check

    Ed, Sep 30, 2004, in forum: VHDL
    Replies:
    18
    Views:
    10,806
    yassen
    Oct 6, 2009
  2. snacktime

    Set parity of a string

    snacktime, Jan 23, 2005, in forum: Python
    Replies:
    8
    Views:
    387
    Peter Hansen
    Jan 26, 2005
  3. Petr Jakes
    Replies:
    2
    Views:
    5,124
    Petr Jakes
    Nov 12, 2005
  4. shakeelsultan

    odd parity checker FSM

    shakeelsultan, Oct 27, 2006, in forum: VHDL
    Replies:
    0
    Views:
    811
    shakeelsultan
    Oct 27, 2006
  5. Herbert Haas

    Parity check of a word

    Herbert Haas, Aug 28, 2005, in forum: C Programming
    Replies:
    15
    Views:
    691
    Krishanu Debnath
    Sep 1, 2005
Loading...

Share This Page