XOR 两个二进制字符串 C++ [英] XOR two Binary Strings c++

查看:24
本文介绍了XOR 两个二进制字符串 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串如下:

STRING1  :        011011110011000

STRING2  :        011001000001000

EXPECTED OUTPUT : 000010110010000

但是,当我尝试使用以下代码对它们进行异或(按位)时,输出为空白.代码:

However, when i try to XOR them(bit-wise) using the following code, the output is blank. Code:

for(int i = 0; i<15; i++)
 {
    final_key[i] = STRING1[i] ^ STRING2[i]; 
    cout<<" XOR = "<<final_key[i];
 }

任何帮助将不胜感激.

推荐答案

您正在尝试一次对 2 个 char 进行异或.试试:

You are trying to XOR 2 char at a time. Try instead:

final_key[i] = ((STRING1[i]-'0') ^ (STRING2[i]-'0')) + '0'; 

说明

有关 ASCII 值,请参阅此处.

Refer to here for ASCII values.

'0'的ASCII值为48,'1'的ASCII值为49.48^49为1,48 ^ 4849 ^ 49 是 0.这些将返回 0 或 1 的值给 char,它代表一个EOF 字符(如果是 0)或 SOH 字符(如果是 1),两者都没有正确输出.

The ASCII value for '0' is 48 and the ASCII value of '1' is 49. 48 ^ 49 is 1, 48 ^ 48 and 49 ^ 49 is 0. These would return a value of 0 or 1 to a char, which would stand for either a EOF char (if it is 0) or a SOH char (if it is one), neither of which are output correctly.

因此,您可能希望在进行 XOR 运算之前将每个 char 转换为一个位(0 或 1).这样你就可以从每个char中减去'0'得到数字的数值,进行异或运算,然后加回'0' 获得正确的输出

Thus you would want to convert each char into a bit (0 or 1) before conducting the XOR operation. Thus you can subtract '0' from each char to get the numrical value of the digit, conduct the XOR operation, then add back '0' to get a proper output

这篇关于XOR 两个二进制字符串 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆