Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to XOR byte arrays in C

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>
#include <string.h>

// XOR two byte arrays of the same length
void xor_bytes(const uint8_t *a, const uint8_t *b, uint8_t *result, size_t len) {
    for (size_t i = 0; i < len; ++i) {
        result[i] = a[i] ^ b[i];
    }
}

// Print byte array as 8-bit binary values
void print_bitset_array(const char *label, const uint8_t *array, size_t len) {
    printf("%s: ", label);
    for (size_t i = 0; i < len; ++i) {
        for (int bit = 7; bit >= 0; --bit)
            printf("%d", (array[i] >> bit) & 1);
        printf(" ");
    }
    printf("\n");
}

int main() {
    uint8_t a[] = {'A', 'e', 'r', 'y', 'n'};
    uint8_t b[] = {'A', 'l', 'b', 'u', 's'};
    size_t len = sizeof(a);

    uint8_t c[len];
    xor_bytes(a, b, c, len);

    print_bitset_array("a", a, len);
    print_bitset_array("b", b, len);
    print_bitset_array("c", c, len);

    printf("c: ");
    for (size_t i = 0; i < len; ++i)
        printf("%d ", c[i]);

    return 0;
}



/*
run:

a: 01000001 01100101 01110010 01111001 01101110 
b: 01000001 01101100 01100010 01110101 01110011 
c: 00000000 00001001 00010000 00001100 00011101 
c: 0 9 16 12 29 

*/

 



answered Jul 12, 2025 by avibootz

Related questions

2 answers 140 views
140 views asked Apr 13, 2023 by avibootz
1 answer 170 views
170 views asked Jun 13, 2015 by avibootz
1 answer 65 views
65 views asked Jul 12, 2025 by avibootz
1 answer 93 views
1 answer 64 views
64 views asked Jul 12, 2025 by avibootz
1 answer 72 views
72 views asked Jul 12, 2025 by avibootz
...