Skip to content

Instantly share code, notes, and snippets.

@yeedle
Last active November 27, 2016 02:53
Show Gist options
  • Save yeedle/d5ca9601ccb922a5c16995374eaea8c2 to your computer and use it in GitHub Desktop.
Save yeedle/d5ca9601ccb922a5c16995374eaea8c2 to your computer and use it in GitHub Desktop.
Converts a number encoded as a String in any radix to an int in decimal representation using Java 8 based on http://stackoverflow.com/a/18552071/4240010
import java.util.*;
import java.util.stream.*;
import java.util.concurrent.atomic.*;
class StringToIntConversion {
public static void main(String[] args) {
String binary = "01110";
System.out.println(Integer.valueOf(binary, 2));
System.out.println(toRadix(binary, 2));
System.out.println(toRadix2(binary, 2));
}
public static int toRadix(String s, int radix) {
char[] c = s.toCharArray();
return (int) IntStream.range(0, c.length)
.mapToDouble(i -> Character.getNumericValue(c[i])*Math.pow(radix, c.length-i-1))
.sum();
}
public static int toRadix2(String s, int radix) {
AtomicInteger i = new AtomicInteger(s.length());
return (int) s.chars()
.mapToDouble(c -> Character.getNumericValue((char)c)*Math.pow(radix, i.decrementAndGet()))
.sum();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment