Marco
Marco

Reputation: 13

C How do XOR between unsigned int pointers

I have two unsigned int pointers with 32 bit and I want do an XOR operation between these unsigned pointers.

char* a = "01110011011100100110111101000011";
char* b = "10111001100011001010010110111101";
unsigned* au = (unsigned*) a;
unsigned* bu = (unsigned*) b;
unsigned* cu = a ^ b;

Error is:

 invalid operands to binary ^ (have ‘unsigned int *’ and ‘unsigned int *’)

Upvotes: 0

Views: 1218

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126213

You have strings, not unsigned integers. You'll need to convert them to unsigned integers before you can do bitwise operations on them:

char* a = "01110011011100100110111101000011";
char* b = "10111001100011001010010110111101";
unsigned au = strtoul(a, 0, 2);
unsigned bu = strtoul(b, 0, 2);
unsigned cu = a ^ b;

Upvotes: 2

R Sahu
R Sahu

Reputation: 206607

Your code needs to work a little harder to pull that off.

  1. Iterate over the strings.
  2. Pull the numbers from the digits.
  3. Perform an XOR between the numbers.
  4. Convert the number to a digit.
  5. Add the resultant digit to the output.

char str1[] = "01110011011100100110111101000011";
char str2[] = "10111001100011001010010110111101";
char* p1 = str1;
char* p2 = str2;
for ( ; *p1 != '\0' && *p2 != '\0'; ++p1, ++p2 )
{
   unsigned int n1 = *p1 - '0';
   unsigned int n2 = *p2 - '0';
   unsigned int n = n1 ^ n2;
   char c = n + '0';

   // Now you can change either a or be to contain the output.
   *p1 = c;
}

// At this point, str1 should contain a string that looks like you performed an XOR between str1 and str2.

Upvotes: 1

Related Questions