Search code examples
rubydes3desparity

Calculate the parity of a byte in Ruby


What's the best way to calculate if a byte has odd or even parity in Ruby? I've got a version working:

result = "AB".to_i(16).to_s(2).count('1').odd?
=> true

Converting a number to a string and counting the "1"s seems a poor way of calculating parity though. Any better methods?

I want to be able to calculate the parity of a 3DES key. Eventually, I'll want to convert even bytes to odd.

Thanks, Dan


Solution

  • Unless what you have is not fast enough, keep it. It's clear and succinct, and its performance is better than you think.

    We'll benchmark everything against array lookup, the fastest method I tested:

    ODD_PARITY = [
      false,
      true,
      true,
      ...
      true,
      false,
    ]
    
    def odd_parity?(hex_string)
      ODD_PARITY[hex_string.to_i(16)]
    end
    
    • Array lookup computes the parity at a rate of 640,000 bytes per second.
    • Bowsersenior's C code computes parity at a rate of 640,000 bytes per second.
    • Your code computes parity at a rate of 284,000 bytes per second.
    • Bowsersenior's native code computes parity at a rate of 171,000 bytes per second.
    • Theo's shortened code computes parity at a rate of 128,000 bytes per second.