Skip to content

Commit 24ad514

Browse files
added Checksum algo and unit tests
1 parent a006205 commit 24ad514

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* A simple Checksum implementation for data validation.
5+
* Calculates an 8-bit checksum of a given byte array.
6+
*/
7+
public final class Checksum {
8+
9+
private Checksum() {
10+
// Private constructor to prevent instantiation
11+
}
12+
13+
/**
14+
* Calculates an 8-bit checksum for the specified input data.
15+
*
16+
* @param data the byte array to checksum
17+
* @return the 8-bit checksum value as an integer
18+
*/
19+
public static int calculateChecksum(byte[] data) {
20+
if (data == null) {
21+
throw new IllegalArgumentException("Input data cannot be null");
22+
}
23+
int checksum = 0;
24+
for (byte b : data) {
25+
checksum = (checksum + b) & 0xFF;
26+
}
27+
return checksum;
28+
}
29+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
import com.thealgorithms.maths.Checksum;
9+
10+
public class ChecksumTest {
11+
12+
@Test
13+
public void testCalculateChecksumNormal() {
14+
byte[] data = {1, 2, 3, 4, 5};
15+
int result = Checksum.calculateChecksum(data);
16+
assertThat(result).isEqualTo(15);
17+
}
18+
19+
@Test
20+
public void testCalculateChecksumEmpty() {
21+
byte[] data = {};
22+
int result = Checksum.calculateChecksum(data);
23+
assertThat(result).isEqualTo(0);
24+
}
25+
26+
@Test
27+
public void testCalculateChecksumNull() {
28+
assertThatThrownBy(() -> Checksum.calculateChecksum(null))
29+
.isInstanceOf(IllegalArgumentException.class);
30+
}
31+
32+
33+
34+
@Test
35+
public void testCalculateChecksumSingleByte() {
36+
byte[] data = {100};
37+
int result = Checksum.calculateChecksum(data);
38+
assertThat(result).isEqualTo(100);
39+
}
40+
41+
@Test
42+
public void testCalculateChecksumMaxByteValue() {
43+
// Tests handling of high byte values close to 255
44+
byte[] data = {(byte) 255};
45+
int result = Checksum.calculateChecksum(data);
46+
assertThat(result).isEqualTo(255);
47+
}
48+
}

0 commit comments

Comments
 (0)