gpt4 book ai didi

java - java中二进制字符串的异或

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:33 25 4
gpt4 key购买 nike

我正在使用以下代码对 2 个字符串进行异或运算

String lseq = "0011111111101111111111111100101101111100110000001011111000010100";
String tseq = "0011111111100000110011001100110011001100110011001100110011001100";

StringBuilder sb = new StringBuilder();

for(int i = 0; i < lseq.length(); i++)
sb.append((lseq.charAt(i) ^ tseq.charAt(i)));

String result = sb.toString();
System.out.println(result);

上面的代码给出了正确的输出:

0000000000001111001100110000011110110000000011000111001011011000

我需要再对一个字符串进行异或运算

String hseq = "0011111111110010010111110100010111100000101101001110000100011110";

如果我尝试 sb.append((lseq.charAt(i) ^ tseq.charAt(i) ^ hseq.charAt(i));

我正在得到结果:

48484848484848484848484948484948494848494848494949484848494848494848494849494848484949494948484848484948494948494949484948484948

这是错误的。我需要帮助对 3 个二进制字符串进行异或运算

最佳答案

我会这样做

private static boolean bitOf(char in) {
return (in == '1');
}

private static char charOf(boolean in) {
return (in) ? '1' : '0';
}

public static void main(String[] args) {
String lseq ="0011111111101111111111111100101101111100110000001011111000010100";
String tseq ="0011111111100000110011001100110011001100110011001100110011001100";
String hseq ="0011111111110010010111110100010111100000101101001110000100011110";

StringBuilder sb = new StringBuilder();

for (int i = 0; i < lseq.length(); i++) {
sb.append(charOf(bitOf(lseq.charAt(i)) ^ bitOf(tseq.charAt(i))
^ bitOf(hseq.charAt(i))));
}

String result = sb.toString();
System.out.println(result);
}

哪些输出

0011111111111101011011000100001001010000101110001001001111000110

关于java - java中二进制字符串的异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20745387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com