Xor operation on two numbers

43 views (last 30 days)
i have two numbers 23 and 47, i have to convert them into binary and then perform the Xor operation how to do that
4评论

Sign in to comment.

Accepted Answer

Bhaskar R
Bhaskar R 20月11日
编辑:Bhaskar R 20月11日
Since decimal to binary conversion may not produce same length of inputs to xor, we need to append 0's before the binary value
in1 = 27;
in2 = 47;
x = DEC2BIN(IN1);
y = dec2bin(in2);
if长度(x)〜=长度(y)
max_len = max(长度(x),长度(y));
x = [repmat('0', 1, max_len-length(x)), x];
y = [repmat('0',1,max_len长度(y)),y];
end
result = xor(x-'0',y-'0');

更多的Answers (1)

John D'Errico
John D'Errico 20月11日
编辑:John D'Errico 20月11日
Use the 2 argument form of dec2bin, comverting to binary. This allows you to insure the two binary equivalents are stored with the same number of bits. So one of the binary forms may now have leading zero bits. Otherwise, dec2bin may leave one result too short for the xor. By computing the number of bits necessary in advance for each number, then we can use that 2 argument form for dec2bin.
接下来,您需要使结果成为逻辑向量,而不是Dec2bin返回的字符形式。虽然看起来像二进制数,但它不是XOR可以直接使用的东西。
最后,对XOR的呼吁做最后一块。
It would look like this:
x = 23;
y = 47;
nbits = floor(log2(max(x,y)))+1;
xb = dec2bin(x,nbits) =='1';
yb = dec2bin(y,nbits) =='1';
结果= XOR(XB,YB);
Did it work? Yes.
xb
xb =
1×6 logical大批
0 1 0 1 1 1
yb
yb =
1×6 logical大批
1 0 1 1 1 1
result
result =
1×6 logical大批
1 1 1 0 0 0
As you can see, xb now has a leading zero bit, as is needed to make the xor happy. As well, xb and yb are now numeric (logical) vectors, the other thing that xor will need.
If you need to convert result back into a decimal integer form, then use bin2dec. Don't forget to convert the binary form from xor back into characters first, else bin2dec will fail. The idea is to add '0' to the binary form, this gives the ascii numeric form for '0' and '1'. Then the function char takes it to characters, and bin2dec gives you an integer.
bin2dec(char(result +'0'))
ans =
56
Could I have done this more compactly? Well, yes. Two lines would have been sufficient, because I never really needed to compute the number of bits in advance. The trick here is to use dec2bin only once, in a "vectorized" call.
b = dec2bin([x,y])=='1'
B =
2×6 logical大批
0 1 0 1 1 1
1 0 1 1 1 1
结果= xor(b(1,:),b(2,:))
result =
1×6 logical大批
1 1 1 0 0 0
您可以看到Dec2bin的矢量化形式智能足以自动留下较小的数字。这允许我们不需要预编译所需的比特数。如果我真的想要以整数形式返回的结果,我也可以这样做。
result = bin2dec(char(xor(B(1,:),B(2,:)) +'0'))
result =
56

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

开始狩猎!