130k views
2 votes
Write a java program that computes a simple checksum of 8-bit integers. this program is based upon the calculation of the checksum value of a ipv4 header, defined by rfc791.

User Juude
by
8.8k points

1 Answer

7 votes

Sure! Here's a Java program that computes a simple checksum of 8-bit integers:

```java
public class ChecksumCalculator {
public static void main(String[] args) {
int[] header = { 0x45, 0x00, 0x00, 0x54, 0x12, 0x34, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 0xC0, 0xA8, 0x01, 0x01, 0xC0, 0xA8, 0x01, 0x02 };
int checksum = calculateChecksum(header);
System.out.println("Checksum: " + Integer.toHexString(checksum));
}

public static int calculateChecksum(int[] header) {
int sum = 0;

for (int i = 0; i < header.length; i += 2) {
sum += (header[i] << 8) + header[i + 1];

if ((sum & 0xFFFF0000) != 0) {
sum &= 0xFFFF;
sum++;
}
}

return ~sum & 0xFFFF;
}
}
```

Step-by-step explanation:
1. In the `main` method, we define an array `header` that represents an IPv4 header. This array contains 20 8-bit integers.
2. We then call the `calculateChecksum` method to compute the checksum of the header.
3. The `calculateChecksum` method takes the `header` array as input and returns an integer representing the checksum value.
4. Inside the `calculateChecksum` method, we initialize a variable `sum` to 0. This variable will store the running sum of the 8-bit integers.
5. We iterate over the `header` array in steps of 2. For each pair of 8-bit integers, we add them to the `sum` variable. We shift the first integer 8 bits to the left and add it to the second integer.
6. If the `sum` variable exceeds 16 bits (i.e., if the most significant bit is set), we truncate the value to 16 bits by performing a bitwise AND operation with `0xFFFF`.
7. If the `sum` variable is still larger than 16 bits, we increment it by 1.
8. Finally, we perform a bitwise complement (~) on the `sum` variable and perform a bitwise AND operation with `0xFFFF` to get the checksum value.
9. The checksum value is then returned to the `main` method and printed as a hexadecimal string.

I hope this helps! Let me know if you have any further questions.

User RonC
by
8.1k points