How do I XOR in a specific spot in my integer?

229 views Asked by At

Could anybody please help me with this? With C I am trying to XOR(^) an int in a specific spot.

These are the steps:

Step 1: Grab and save the leftmost 4 bits before shifting

Step 2: Then I shift left by doing this on my code num << 4

Step 3: Then XOR in num from 17-20 with the leftmost 4 bits that were stored in step 1.

For Example:

Say I have an

unsigned int num = 7

this in binary would be

0000 0000 0000 0000 0000 0000 0000 0111

Before shifting to the left by 4, I want to grab and save the leftmost 4 bits 0000. Then I want to XOR from 17-20 of my num with the leftmost 4 bits that I saved.

This is for a hashing code I am creating. There is more to my code, but I am only sharing the part I am stuck and confused.

I have tried looking for other similar questions, but I don't understand what they are doing. If I could get an explanation that would be great.

1

There are 1 answers

0
chux - Reinstate Monica On

OP is assuming an unsigned is 32 bit. Let us be specific:

uint32_t num = 7;

to grab the leftmost 4 bits of my num

uint32_t left4 = num >> (32-4);

I just want to XOR from 16-21 of my num. ... grab the leftmost 4 bits of my num then with those leftmost 4 bits then XOR in the specific location

Apparently OP wants to XOR the 4 bits 17-20.

left4shifted = left4 << 17;
unint32_t result = num ^ left4shifted;

but I am trying to create a hash code.

Best to post the whole algorithm.