diff --git a/src/main/java/com/thealgorithms/maths/Checksum.java b/src/main/java/com/thealgorithms/maths/Checksum.java new file mode 100644 index 000000000000..9964aa9caec7 --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/Checksum.java @@ -0,0 +1,23 @@ +package com.thealgorithms.maths; + +/** + * Checksum implementation for data validation. + * Should calculate an 8 bit checksum of a given byte array + */ +public final class Checksum { + + private Checksum() { //priv constructor + } + +//Calc an 8 bit checksum for the specified input data. + public static int calculateChecksum(byte[] data) { + if (data == null) { + throw new IllegalArgumentException("Input data cannot be null"); + } + int checksum = 0; + for (byte b : data) { + checksum = (checksum + b) & 0xFF; + } + return checksum; + } +} \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/ChecksumTest.java b/src/test/java/com/thealgorithms/ChecksumTest.java new file mode 100644 index 000000000000..e2902be3419e --- /dev/null +++ b/src/test/java/com/thealgorithms/ChecksumTest.java @@ -0,0 +1,48 @@ +package com.thealgorithms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +import com.thealgorithms.maths.Checksum; + +public class ChecksumTest { + + @Test + public void testCalculateChecksumNormal() { + byte[] data = {1, 2, 3, 4, 5}; + int result = Checksum.calculateChecksum(data); + assertThat(result).isEqualTo(15); + } + + @Test + public void testCalculateChecksumEmpty() { + byte[] data = {}; + int result = Checksum.calculateChecksum(data); + assertThat(result).isEqualTo(0); + } + + @Test + public void testCalculateChecksumNull() { + assertThatThrownBy(() -> Checksum.calculateChecksum(null)) + .isInstanceOf(IllegalArgumentException.class); + } + + + + @Test + public void testCalculateChecksumSingleByte() { + byte[] data = {100}; + int result = Checksum.calculateChecksum(data); + assertThat(result).isEqualTo(100); + } + + @Test + public void testCalculateChecksumMaxByteValue() { + // Tests handling of high byte values close to 255 + byte[] data = {(byte) 255}; + int result = Checksum.calculateChecksum(data); + assertThat(result).isEqualTo(255); + } +} \ No newline at end of file