如何使用或运算符组合2个字符串? [英] how to combine 2 string using or operator?
问题描述
String a="b5a99e49708ecf072f189b4f85007c76990ef305";
String b="a7d55b1a392a1f34ab95453817fdd49df140c486";
示例我将字符串转换为十进制"1".是6位.我该如何做7位?并使用或运算符字符串a和b;
Example i converted string to decimal "1". it was 6 bits. how do i do it 7bits? and use or operator string a and b;
这是我的代码
char[] c = a.toCharArray();
char[] d = b.toCharArray();
for (int i = 0; i < str.length(); i++)
{
r += Integer.toBinaryString(c[i]|d[i]);
}
推荐答案
如果我正确理解,您只需要在二进制字符串中添加正确数量的零即可,所以总共有7位.生成少量固定数量字符的标准技巧是在该字符的恒定字符串上使用String.substring()
.由于char
可以容纳16位,所以我们永远不需要超过16个零:
If I have understood correctly, you just need to prepend the correct number of zeroes to your binary string so there are 7 bits in all. The standard trick to generate a small fixed number of a character is to use String.substring()
on a constant string of that character. Since a char
fits in 16 bits, we will never need more than 16 zeroes:
String binaryString = Integer.toBinaryString(ch);
int missingZeroes = desiredNumberOfBits - binaryString.length();
if (missingZeroes > 0) {
binaryString = "0000000000000000".substring(0, missingZeroes) + binaryString;
}
System.out.println(binaryString);
如果ch
是持有1
的char
,则上面的打印内容
If ch
is a char
holding a 1
, the above prints
0110001
如果需要的话,您可以填写c[i] | d[i]
而不是ch
.
You can fill in c[i] | d[i]
instead of ch
if that is what you require.
您可能要添加防御性检查,以确保Integer.toBinaryString()
中的字符串不是太长.
You may want to add a defensive check that the string from Integer.toBinaryString()
is not already too long.
这篇关于如何使用或运算符组合2个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!