Advertisement
SAURAVKR

Untitled

Sep 10th, 2024
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. // Function to compute the 2's complement checksum
  7. unsigned short computeChecksum(vector<unsigned short>& data) {
  8. unsigned long sum = 0;
  9.  
  10. // Sum all 16-bit words
  11. for (unsigned short word : data) {
  12. sum += word;
  13.  
  14. // If overflow occurs (i.e., sum exceeds 16 bits), wrap around
  15. if (sum & 0x10000) {
  16. sum = (sum & 0xFFFF) + 1; // Add the carry back to the lower 16 bits
  17. }
  18. }
  19.  
  20. // One's complement (invert the bits)
  21. return ~sum & 0xFFFF;
  22. }
  23.  
  24. int main() {
  25. // Example data: vector of 16-bit values (you can modify this as needed)
  26. vector<unsigned short> data = {0x1234, 0xABCD, 0x4567, 0x89EF}; // Example data values
  27.  
  28. // Compute the checksum
  29. unsigned short checksum = computeChecksum(data);
  30.  
  31. // Print the checksum result
  32. cout << "Checksum: 0x" << hex << checksum << endl;
  33.  
  34. return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement