# How to XOR two binary numbers having different lengths?

If we have:

x = 1101 and y = 101

How to XORing these numbers?

• Why would you want to XOR these numbers? – Yuval Filmus Oct 23 '15 at 7:46
• You already asked essentially the same question on Stack Overflow: stackoverflow.com/q/31520787/781723. It would have been better to mention the comments you already got over there when you asked it here, and link to the pre-existing question on Stack Overflow in this post. – D.W. Oct 10 '16 at 3:25

There are multiple ways to interpret this XOR.

The most common one is that you XOR bit-wise, and that these strings represent numbers, so adding 0 to the left doesn't change their value.

Then $5 \equiv 101 \to 0101$ and then you XOR bit-wise.

x 1101
y 0101
------- XOR
1000


which gives 8, if we are talking about unsigned numbers. However, the above depends on my understanding of your system. Change the assumptions, change the results.

• What if we have two binary numbers first one 8-bits and the second one is 55-bits. Is there another method to xorring them withot add "0"? – SHdotCom Oct 23 '15 at 12:31
• what is the aim of XOR'ing them? – Ran G. Oct 23 '15 at 13:57

Look first you should know is your numbers in Signage system value or not if they are in Signage system value you should do some stuff 1_ your number is positive (it means the last bit is zero such as 101 this number is -3) so in this case if you want to increase the number of bits you should add 1 to last bit . in your case the number 101 turns into 1101 and 1101 xor 101 turns into 1101 xor 1101 and the answer is 0000 2_ but if your numbers were normal (not in Signage system value mode) very easy you add zero to last bit . in your case 1101 xor 101 become 1101 xor 0101 and the answer is 1000

• XOR is a logical operation, so it doesn't make too much sense to sign-extend numbers being XORed. – Yuval Filmus Apr 27 '18 at 19:05

if x and y are integer values, then

int XOR(int x,int y)
{
return x^y;
}


whereas, if x and y are strings, then

string XOR(string x,string y)
{
auto temp= bitset<4>(x) ^ bitset<4>(y);
string u;
u=temp.to_string();
return u;
}

• In the notation of your 2nd code block, the question is about bitset<4>(x) ^ bitset<3>(y). – greybeard Dec 13 '19 at 3:28