0

I have two strings in the following format:

"11010"
"00101"

Both are binary representations. I want to OR these numbers and get the result as follows:

"11111"

Any idea on how to get it done using Java?

Upadte:

This is not a duplicate of mentioned question. I am performing OR operator on binary number represented in String format

KItis
  • 5,476
  • 19
  • 64
  • 112

3 Answers3

2

You can use the Integer.parse method

int x1 = Integer.parseInt("11010", 2);
int x2 = Integer.parseInt("00101", 2);
int val = x1 | x2;
String binOr = Integer.toBinaryString(val);
Harsh Poddar
  • 2,394
  • 18
  • 17
  • 2
    With different input this can make the resulting string shorter than the input, by dropping leading zeroes. (that's not wrong, just something to be aware of) – harold Mar 19 '16 at 17:46
1

There is so many obvious ways, such as converting to a BigInteger, or string manipulation but this is a less obvious one, which of course you cannot pass of as your own homework, but you might learn something.

public static String or(String a, String b) {
    assert a.length() == b.length();
    char[] ac = a.toCharArray();
    for(int i = 0; i < ac.length; i++)
        ac[i] |= b.charAt(i);
    return new String(ac);
}

I leave it as an exercise for you to work out why this works. ;)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Try this by using the Integer class:

public static void main(String[] args) {
    // "11010" "00101"

    // 1. parse the strings to integer
    final int nibble1 = Integer.parseInt("11010", 2);
    final int nibble2 = Integer.parseInt("00101", 2);
    // 2. make the bitwise operation and bulk the result in the int result
    final int result = nibble1 | nibble2;
    // print the result as integer
    System.out.println(result);
    // or print it as binary
    System.out.println(Integer.toBinaryString(result));
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97