hektor
hektor

Reputation: 1025

How do you perform an XOR operation of a unsigned long integer and a character array in C?

These are my two variables with which I want to do an xor operation (in C).

unsigned long int z=0xB51A06CD;

unsigned char array[] = {0xF0,0xCC,0xAA,0xF0};

desired output= 0X45D6AC3D

I know I cannot do a simple z ^ array, because it's a character array and not a single character. Will I have to do XOR of one byte at a time or is there a function for it in C?

I am trying all kinds of crazy things to get it done, but failing miserably all the time. If anyone can help me out with a small code snippet or at least a rough idea, I would be extremely grateful.

Upvotes: 2

Views: 4381

Answers (4)

TJD
TJD

Reputation: 11896

As others mentioned, you have to worry about endianness and size of long. Here's how to make it safe: 1) instead of unsigned long, use uint32_t (from inttypes.h), to be sure you get a 4 byte type. 2) use htonl() as a platform-independent way to ensure you interpret the array as a big-endian value

z ^ htonl(*(uint32_t *)array);

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263277

unsigned long int z=0xB51A06CD;

unsigned char array[] = {0xF0,0xCC,0xAA,0xF0};
unsigned long tmp;
memcpy(&tmp, array, sizeof tmp);
... z ^ tmp ...

Note that this still makes a number of non-portable assumptions: that unsigned long is 4 bytes, and that the system's endianness is what you expect it to be.

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

Just make an unsigned long int out of your array (warning, it depends on the machine endianness!):

unsigned long int z=0xB51A06CD;
unsigned char array[] = {0xF0,0xCC,0xAA,0xF0};

unsigned long int w = 0;
w |= array[0] << 0;
w |= array[1] << 8;
w |= array[2] << 16;
w |= array[3] << 24;

unsigned long output = z ^ w;

Upvotes: 1

sidyll
sidyll

Reputation: 59287

Cast the array, which is treat as a pointer to the first element in an expression like this one, to a long pointer instead of char pointer , and dereference it.

unsigned long result = z ^ *(unsigned long *)array;

Upvotes: 3

Related Questions