×

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender to receiver. Using Hamming code, we may implement the code in Java to find and fix problems.

Because R.W. Hamming created the code to find and fix faults, it is known as Hamming code.

If the data bit count is 7, then the redundant bit count can be determined using the formula: = 24 7 + 4 + 1. As a result, there are 4 parity bits in total. To verify that the total number of 1s in the binary data is even or odd, a parity bit is a bit that is attached to the data. Error detection uses parity bits. Parity bits come in two varieties:

Even parity bit: For a specific set of bits, the number of ones is calculated in the case of even parity. If the count is odd, the parity bit value is set to 1, making the total number of 1 occurrence even. If there are an equal number of 1s in each group of bits, the parity bit has no value.

odd parity - In this scenario, the number of ones is counted for a certain group of bits. If that count is even, the parity bit value is set to 1, making the total distribution of 1s odd. If there are no more than enough odd bits in a group of bits, the parity bit has no value.

In mistake detection and repair, redundant bits and parity bits are crucial. In order to ensure that no bits were lost during the data transmission, redundant bits are extra binary bits that are added to the original data bits and are prepared to be passed from sender to receiver.

To determine if the total number of 1s is even or odd, parity bits are additional bits that are added to the original data (binary bits).

Explore the area to learn more about parity, redundancy, and Hamming code.

General Hamming Code Algorithm

For error detection and correction, we use parity bits, and the technique for doing so is called Hamming code. Following are the steps for Hamming code:

  1. The bit locations are initially written in binary form. The bit locations ought to be ordered from 1 to 32. (1, 10, 11, 100, etc.).
  2. We designate all bits that are powers of 2 as parity bits (1, 2, 4, 8, etc.).
  3. The remaining bit positions are all designated as data bits.
  4. Based on its bit position in binary representation, each data bit is a part of a distinct set of parity bits.
  5. The eighth parity bit covers all bit locations (8-15, 24-31, 40-47, etc.) whose binary show has 1 in the fourth position from the least bit.
    • In the binary representation of the fourth parity bit, the third bit from the least bit spans all the bit locations (4-7, 12-15, 20-23, etc.).
    • The second parity bit covers all bit locations (2, 3, 6, 7, etc.) whose binary show has 1 in the second position from the least significant bit.
    • The second parity bit covers all bit locations (1, 3, 5, 7, 9, etc.) whose binary show has 1 in the least significant place.
    • When the parity position and bit position's bitwise AND are non-zero, each parity bit covers all the bits.
  6. Since we check for even parity, set a parity bit to 1 if the total number of ones in the places it examines is odd.
  7. If all of the ones in the positions it examines are even, set the parity bit to 0.
Hamming Code in Java

Positioning extra bits - These redundant bits are positioned at locations that are a power of two higher than the original position.

similar to the illustration given above

There are 7 bits of data.

There are 4 superfluous bits.

There are 11 bits in all.

The redundant bits are positioned at the power of 2- 1, 2, 4, and 8corresponding places.

Hamming Code in Java

The bits will be arranged as follows, assuming the data to be conveyed is 1011001:

Hamming Code in Java

The parity bits are determined:

All bit positions with a 1 in the least significant position in their binary representation are used to determine the R1 bit using parity check. R1: bits 1, 3, 5, 7, 9, 11.

Hamming Code in Java

We look for even parity and then look for the superfluous bit R1. Since there are exactly as many 1s as 0s in all of the bit positions corresponding to R1, the value of R1 (the parity bit's value) is 0.

Hamming Code in Java

We look for equal parity and then look for the superfluous bit R2. Because there are more odd numbers than even ones in all of the bit positions corresponding to R2, the value of R2 (the parity bit's value) is 1.

With a 1 in the third position from the least bit, a parity check at each location in a binary show identifies the R4 bit. R4: bits 4, 5, 6, 7

Hamming Code in Java

We look for even parity and then look for the redundant bit R4. Since there are more odd numbers than even ones in all of the bit places corresponding to R4, R4's parity bit value equals 1.

Using a parity check at each bit location for a binary representation with a 1 in the fourth position from the least significant bit, the R8 bit is identified. R8: bit 8,9,10,11

Hamming Code in Java

We look for even parity and then look for the redundant bit R8. Since there are exactly as many 1s as 0s in R8's corresponding bit places, R8's parity bit value is 0. Thus, the information conveyed is:

Hamming Code in Java

Error detection and correction: Assume that during data transmission, the 6th bit in the example above was altered from 0 to 1, which would result in new parity values for the binary number:

Hamming Code in Java

The binary number 0110 is generated by the bits, and its decimal representation is 6. Bit 6 therefore contains a mistake. The 6th bit is altered from 1 to 0 to fix the issue.

//
Package Example;  
import java.util.*;  


// to implement the Hamming Code feature in Java, develop an HC class.
class HC {  


    // main() method start  
    public static void main(String args[])   
    {  
        // declare variables and array  
        int s, HCS, errorposition;  
        int a[];  
        int hammingCode[];  
        // create an instance of the scanner class to hold user input.
        Scanner sn = new Scanner(System.in);  
System.out.println("Enter the data's bit size.");  
        s = sn.nextInt();  
        // initialize array  
        a = new int[s];  
        //get the user to provide the info we wish to send
        for(int j = 0 ; j < s ; j++) {  
System.out.println("Enter " + (s - j) + "-bit of the data:");  
            // data entered by the user to populate an array
            a[s - j - 1] = sc.nextInt();  
        }  


        // print the user entered data  
System.out.println("The data which you enter is:");  
        for(int k = 0 ; k < s ; k++) {  
System.out.print(arr[s - k - 1]);  
        }  
System.out.println();   // for next line  


        // Using the getHammingCode() method and adding the result to the hammingCode array.
HCode = getHCode(a);  
HCS = HCode.length;  


System.out.println("Your data's produced hamming code is:");  
        for(int i = 0 ; i<HCS; i++) {  
System.out.print(hammingCode[(HCS - i - 1)]);  
        }  
System.out.println();   // for next line  


        // The difference between the original data and the returned hammingCode is represented by the extra parity bits.
System.out.println("Enter the position of a bit to change the original data in order to discover errors at the receiver end."  
                + "(0 for no error):");  
errorPosition = sn.nextInt();  


        // close Scanner class object  
sn.close();  


        // Verify if the user-entered location is zero (0).
        if(errorPosition != 0) {  
            // change a user-entered position's bit
HCode[errorPosition - 1] = (HCode[errorPosition - 1] + 1) % 2;  
        }  


        // print sent data to the receiver  
System.out.println("Sent Data is:");  
        for(int k = 0; k <HCS; k++) {  
System.out.print(hammingCode[HCS - k - 1]);  
        }  
System.out.println();   // for next line  
receiveData(HCode, HCS - a.length);  
    }  
    // construct a method called getHammingCode() that returns the hamming code for the data we wish to deliver.
    static int[] getHCode(int data[]) {  
        // define an array that will contain the data's hamming code.
// RD = return Data
        int RD[];  
        int s;  
        // code to get the required number of parity bits  
        int i = 0, parityBits = 0 ,j = 0, k = 0;  
        s = data.length;  
        while(i< s) {  
            // The current location (number of bits traversed + number of parity bits + 1) must equal 2 powers of parity bits.
            if(Math.pow(2, parityBits) == (i + parityBits + 1)) {  
parityBits++;  
            }  
            else {  
i++;  
            }  
        }  


        //The RD's size is equal to the combined size of the original data and the parity bits.
RD = new int[s + parityBits];  


        // We initialise the RD array with '2' to represent an unset value in the parity bit location.


        for(i = 1; i<= RD.length; i++) {  
            // condition to find parity bit location  
            if(Math.pow(2, j) == i) {  


RD[(i - 1)] = 2;  
j++;  
            }  
            else {  
RD[(k + j)] = data[k++];  
            }  
        }  
        // Set even parity bits at parity bit locations using a for loop.
// PB = parity bit
        for(i = 0; i<PB; i++) {  


RD[((int) Math.pow(2, i)) - 1] = getPB(RD, i);  
        }  


        return RD;  
    }  


    // develop a method called getPB() that returns parity bits dependent on power
    static int getPB(int RD[], int pow) {  
        int PB = 0;  
        int s = RD.length;  


        for(int i = 0; i< s; i++) {  


  // Verify whether or not RD[i] contains an unset value.
            if(RD[i] != 2) {  


                // If not, we increase the value of the index in k by 1 to save it.


                int k = (i + 1);  


                // binary conversion of the value of k
                String sr = Integer.toBinaryString(k);  


 //We now check the value there to see if the binary value of index has a bit set to 1 at the 2(power) location. Depending on whether the value is 1 or 0, we will decide the parity value.


                int temp = ((Integer.parseInt(sr)) / ((int) Math.pow(10, p))) % 10;  
                if(temp == 1) {  
                    if(RD[i] == 1) {  
PB = (PB + 1) % 2;  
                    }  
                }  
            }  
        }  
        return PB;  
    }  


    // To find errors in the received data, create the receiveData() method.
    static void receiveData(int data[], int PBs) {  


        // declare variable pow, which we use to get the correct bits to check for parity.  
        int p;  
        int s = data.length;       
        //establish parity array to store the parity check value
        int parityArray[] = new int[PBs];  
        // For recording the integer value of the error location, we utilise the errorLocation string.
        String errorLocation = new String();  
        // To check the parities, use a for loop.
        for(p = 0; p <PBs; p++) {  
            // to extract the bit from 2, use a for loop (power)
            for(int i = 0; i< s; i++) {  
                int j = i + 1;  
                // binary conversion of the value of j
                String sr = Integer.toBinaryString(j);  
                // find bit by using sr
                int bit = ((Integer.parseInt(sr)) / ((int) Math.pow(10, pow))) % 10;  
                if(bit == 1) {  
                    if(data[i] == 1) {  
parityArray[p] = (parityArray[p] + 1) % 2;  
                    }  
                }  
            }  
errorLocation = parityArray[p] + errorLocation;  
        }  
        // This provides the values for the parity check equation. We will now use these numbers to determine if there is a single bit issue and subsequently fix it.
        // To determine if a single bit mistake exists or not, we use the parity check equivalent values provided by errorLocatiion. If it's there, we fix it.
        int finalLocation = Integer.parseInt(errorLocation, 2);  
        // check whether the finalLocationa value is 0 or not  
        if(finalLocation != 0) {  
System.out.println("Error is found at location " + finalLocation + ".");  
            data[finalLocation - 1] = (data[finalLocation - 1] + 1) % 2;  
System.out.println("the problem is fixed and the code is:");  
            for(int i = 0; i< s; i++) {  
System.out.print(data[s - i - 1]);  
            }  
System.out.println();  
        }  
        else {  
System.out.println("The data that was received is flawless.");  
        }  
        // print the original data  
System.out.println("The data sent from the sender:");  
        p = PBs - 1;  
        for(int k = s; k > 0; k--) {  
            if(Math.pow(2, p) != k) {  
System.out.print(data[k - 1]);  
            }  
            else {  
                // decrement value of pow  
                p--;  
            }  
        }  
System.out.println();   // for next line  
    }  
}  

Output:

Enter the data's bit size
7
Enter 7-bit of the data:
1
Enter 6-bit of the data:
1
Enter 5-bit of the data:
0
Enter 4-bit of the data:
1
Enter 3-bit of the data:
0
Enter 2-bit of the data:
0
Enter 1-bit of the data:
1
The data which was given is:
11001001
The hamming code generated for given data:
11001001101
For detecting error at the receiver end, enter position of a bit to alter original:
3
Sent data is:
11001001001
Error is found at position 3.
After correcting the error, the code is:
11001001101
The data sent from the sender:
1101001

Related Topics

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.