LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 7

XOR and sum checksums with a Byte typedef in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links