Reputation: 673
I have a string with the value 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
.
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++;
}
}
Upvotes: 3
Views: 2318
Reputation: 2440
You can do this using XOR
operation
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;
}
Upvotes: 1
Reputation: 136152
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());
Upvotes: 5
Reputation: 905
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.
Upvotes: 1
Reputation: 283921
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:
b ^= 1;
Which works on both binary and ASCII values of digits.
Upvotes: 1
Reputation:
StringUtils.replaceChars
from common-lang might help here:
StringUtils.replaceChars("0111000000", "01", "10");
Upvotes: 1
Reputation: 30485
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.
Say for example your bit-string has a fixed 10 bits. Then you can mask off the unwanted high-end bits with: value & 0x2ff
.
If the number of bits in the bit-string is variable:
value & ((1 << nBits) - 1)
Upvotes: 1