0

I have a 32-bit long string of 0s and 1s. I just want this string to be flipped just like binary bits. That is, 0s are to be replaced with 1s and 1s with 0s. I tried doing this replacement with this code in Java:

String flippedBit = StringUtils.replaceEach(PadChar,
        new String[]{"0","1"}, new String[]{"1","0"}, false); 

But I get this error:

The method replaceEach(String, String[], String[]) in the type StringUtils is not applicable for the arguments (String, String[], String[], boolean)

Again, I have to store this string in an Integer by first converting it into 32-bit binary.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72
Ataul Haque
  • 93
  • 2
  • 9
  • 1
    So why are you adding the boolean? `StringUtils` doesn't like it when you add the boolean. – Makoto Feb 16 '15 at 05:29

2 Answers2

2

I would iterate the bits of some int v and flip them like

String str = Integer.toBinaryString(v);
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
    sb.append(ch == '1' ? '0' : '1');
}
return Integer.parseInt(sb.toString(), 2);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Sounds like this official nuts & bolts tutorial provides exactly what you're after:

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0".

That is, assuming you're working with the actual bits (in which case this would save you converting to a String and back), and not a String to start with (in which case you're better off with @ElliottFrisch's answer.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72