Aod Ren
Aod Ren

Reputation: 679

Convert Strings of 0 & 1 into bytes

I have two strings:

String a = "11111";
String b = "10001";

I'd like to make a bitwise comparison wih "&" operator.

What would be the best way to do it ?

Upvotes: 3

Views: 1963

Answers (3)

Tunaki
Tunaki

Reputation: 137094

  1. First, convert each binary String into a long value with Long.parseLong(s, 2). This method will parse the given String using a radix of 2, meaning that it should interpret the String as binary.
  2. Calculate the bitwise comparison with & on the two long values.
  3. Convert that back into a binary String with Long.toBinaryString(i).

Here's a sample code:

public static void main(String[] args) {
    String a = "11111";
    String b = "10001";
    long la = Long.parseLong(a, 2);
    long lb = Long.parseLong(b, 2);
    long lc = la & lb;
    String c = Long.toBinaryString(lc);

    System.out.println(c); // prints 10001
}

Another way without using primitive long value would be to do it manually by looping over the digits and storing the & result of their code points in a StringBuilder:

public static void main(String[] args) {
    String a = "11111";
    String b = "10001";

    StringBuilder sb = new StringBuilder(a.length());
    for (int i = 0; i < a.length(); i++) {
        sb.appendCodePoint(a.codePointAt(i) & b.codePointAt(i));
    }
    String c = sb.toString();

    System.out.println(c);
}

Upvotes: 7

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

Use parseLong with a radix of 2 (you may also use the similar functions from the Byte and Integer classes, depending on the max size of you string):

long ba = parseLong(a, 2);
long bb = parseLong(b, 2);
long bc = ba & bb;

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86409

You can use either Integer.parseInt( String s, int radix) or Long.parseLong( String s, int radix).

String a = "11111";
String b = "10001";
int ia = Integer.parseInt( a, 2);
int ib = Integer.parseInt( b, 2 );
int c = ib & ic; 

Upvotes: 0

Related Questions