简体   繁体   English

按位不对一串位操作

[英]Bitwise not operation on a string of bits

I have a string with the value 0111000000 . 我有一个值为0111000000的字符串。 How can I perform a bitwise not operation on this string? 如何对此字符串执行按位运算?

If I convert it to an integer, use the ~ operator and convert it back to a binary string, the resulting string has extra bits. 如果我将它转换为整数,使用~运算符并将其转换回二进制字符串,结果字符串有额外的位。 I want the output to be exactly 1000111111 . 我希望输出正好是1000111111

The following code works fine, but it's not a good method. 以下代码工作正常,但它不是一个好方法。 Is there another better way of doing this? 还有另一种更好的方法吗?

   String bstr="";
   while(m!=str.length())
   {             
        char a=str.charAt(m);
        if(a=='1')
        {
             a='0';
             bstr=bstr+a;
             m++;   
        }
        else
        {
             a='1'; 
             bstr=bstr+a;
             m++;
         }
}

try this 尝试这个

    char[] a = s.toCharArray();
    for(int i = 0; i < a.length; i++) {
        a[i] = a[i]=='0' ? '1' : '0';
    }
    s = new String(a);

this also works fine 这也行得很好

    int i = ~Integer.parseInt(s, 2);
    String tmp = Integer.toBinaryString(i);
    s = tmp.substring(tmp.length()- s.length());

Keep track of how many bits there are in your bit-string. 跟踪位串中的位数。 After converting to an integer and using a ~value operation to flip the bits, use a bit-mask to remove the unwanted 1 high-end bits. 转换为整数并使用~value操作翻转位后,使用位掩码删除不需要的1个高端位。

Say for example your bit-string has a fixed 10 bits. 比如说你的位串有一个固定的10位。 Then you can mask off the unwanted high-end bits with: value & 0x2ff . 然后,您可以使用: value & 0x2ff屏蔽不需要的高端位。

If the number of bits in the bit-string is variable: 如果位串中的位数是可变的:

value & ((1 << nBits) - 1)

来自common-lang的StringUtils.replaceChars可能会有所帮助:

StringUtils.replaceChars("0111000000", "01", "10");

You should use string builder so you are able to change individual bits without creating many many garbage strings. 您应该使用字符串构建器,这样您就可以更改单个位而无需创建许多垃圾字符串。 Also you can flip single bits using XOR: 您也可以使用XOR翻转单个位:

b ^= 1;

Which works on both binary and ASCII values of digits. 哪个适用于数字的二进制和ASCII值。

maybe this will work: 也许这会奏效:

String result = Integer.toBinaryString(~(Integer.parseInt("0111000000",2)));

converts binary String to int, use bitwise not operator to invert, then convert back to binary string. 将二进制String转换为int,使用按位非运算符反转,然后转换回二进制字符串。

You can do this using XOR operation 您可以使用XOR操作执行此操作

public String xorOperation(String value) {
    String str1 = value;
    long l = Long.parseLong(str1, 2);
    String str2 = "";
    for (int i = 0; i < str1.length(); i++) {
        str2 = str2 + "1";
    }
    long n = Long.parseLong(str2, 2);
    long num = l ^ n;
    String bininaryString = Long.toBinaryString(num);
    System.out.println(bininaryString);
    return bininaryString;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM