Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- // Function to compute the 2's complement checksum
- unsigned short computeChecksum(vector<unsigned short>& data) {
- unsigned long sum = 0;
- // Sum all 16-bit words
- for (unsigned short word : data) {
- sum += word;
- // If overflow occurs (i.e., sum exceeds 16 bits), wrap around
- if (sum & 0x10000) {
- sum = (sum & 0xFFFF) + 1; // Add the carry back to the lower 16 bits
- }
- }
- // One's complement (invert the bits)
- return ~sum & 0xFFFF;
- }
- int main() {
- // Example data: vector of 16-bit values (you can modify this as needed)
- vector<unsigned short> data = {0x1234, 0xABCD, 0x4567, 0x89EF}; // Example data values
- // Compute the checksum
- unsigned short checksum = computeChecksum(data);
- // Print the checksum result
- cout << "Checksum: 0x" << hex << checksum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement