javaalgorithmhamming-code

Hamming Code: Number of parity bits


I'm trying to write a method in java that will take an input of any number of 0 or 1 digits and output that line after being encoded with Hamming Code.

I have managed to write the code when knowing the number of digits the input will have (in this case 16) because knowing the number of digits in the input, I immediately know the number of parity bits there have to be added (5 in this case) to a total of 21 digits in the final output. I am working with int arrays so I need to declare a size in the beginning and my code works based on those exact sizes.

Can you guys think of any way/algorithm that can give me the number of digits the output will have (after adding the relevant parity digits to the number of input digits) based solely on the number of input digits?

Or do I have to tackle this problem in a totally different way? Any suggestions? Thank you in advance!

Cheers!


Solution

  • From my understanding, you get your 6th parity bit at 32 bits of input, 7th at 64, etc. so what you need is floor(lg(n)) + 1, which in java you can get by using 32 - Integer.numberOfLeadingZeros(n).

    Assuming your input is made up entirely of 0s and 1s, you would do

    int parityDigits = 32 - Integer.numberOfLeadingZeros(input.length());