Using typedef uint8_t Byte;, compute an 8-bit XOR checksum and an 8-bit additive checksum of a message.
Solution
main.c
#include <stdint.h>
#include <stdio.h>
#include <string.h>
typedef uint8_t Byte;
Byte xor_checksum(const Byte *data, size_t n) {
Byte c = 0;
for (size_t i = 0; i < n; i++)
c ^= data[i];
return c;
}
Byte sum_checksum(const Byte *data, size_t n) {
Byte c = 0;
for (size_t i = 0; i < n; i++)
c = (Byte) (c + data[i]); /* wraps modulo 256 */
return c;
}
int main(void) {
const char *msg = "LearnFrenzy";
const Byte *bytes = (const Byte *) msg;
size_t n = strlen(msg);
printf("xor 0x%02X, sum 0x%02X\n", xor_checksum(bytes, n), sum_checksum(bytes, n));
return 0;
}
Output Verified by compiling and running
xor 0x68, sum 0x70
The Byte alias says "raw 8-bit data" and guarantees the 8-bit wrap-around that a checksum relies on. Reading characters through const Byte * treats the text as unsigned bytes.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!