Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #251 Parse binary digits

Extract integer value i from its binary string representation s (in radix 2)
E.g. "1101" -> 13

Integer i = Integer.valueOf(s, 2);

The second argument in the valueOf method denotes the radix, or base, of the said value.
int i = s.chars()
    .map(x -> x - '0')
    .reduce(0, (a, b) -> a * 2 + b);
import java.math.BigInteger;
int i = new BigInteger(s, 2).intValue();
(def i (read-string (str "2r" s)))

New implementation...