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,900 questions

51,831 answers

573 users

How to use bitwise XOR "^" in C

1 Answer

0 votes
#include <stdio.h>

char *toBinFormat(int n);

int main(int argc, char **argv) 
{ 
    // bit level XOR (^)(exclusive or) 
    // result is 0 when we have two zeroes or two ones
    // result is 1 when one of the bits is 1 and the other is zero
    // with XOR you can toggle the bits between 1 and 0
    
    char tmp;
    
    tmp = 7 ^ 1; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 1, toBinFormat(1));
    printf("tmp = 7 ^ 1 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 ^ 3;
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 3, toBinFormat(3));
    printf("tmp = 7 ^ 3 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 ^ 7;
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("tmp = 7 ^ 7 = %3d = %s\n\n", tmp, toBinFormat(tmp));
   
    tmp = 7 ^ 32; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 32, toBinFormat(32));
    printf("tmp = 7 ^ 32 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 ^ 8; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 8, toBinFormat(8));
    printf("tmp = 7 ^ 8 = %3d = %s\n\n", tmp, toBinFormat(tmp));
   
    return(0);
}

char *toBinFormat(int n)
{
    static char binary_value[9]; // without static binary_value is a local 
                                 // array that disappear after return
    int i;
    
    for(i = 0; i < 8; i++)
    {
        binary_value[i] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    binary_value[i] = '\0';

    return binary_value;
}

/*
run:

  7 = 00000111
  1 = 00000001
tmp = 7 ^ 1 =   6 = 00000110

  7 = 00000111
  3 = 00000011
tmp = 7 ^ 3 =   4 = 00000100

  7 = 00000111
  7 = 00000111
tmp = 7 ^ 7 =   0 = 00000000

  7 = 00000111
 32 = 00100000
tmp = 7 ^ 32 =  39 = 00100111

  7 = 00000111
  8 = 00001000
tmp = 7 ^ 8 =  15 = 00001111


*/

 



answered Jun 13, 2015 by avibootz

Related questions

2 answers 141 views
141 views asked Apr 13, 2023 by avibootz
1 answer 61 views
61 views asked Jul 12, 2025 by avibootz
2 answers 204 views
1 answer 174 views
2 answers 327 views
1 answer 59 views
59 views asked Jul 11, 2025 by avibootz
...