How can I detect integer overflow on 32 bits int?

Math.addExact throws exception on overflow Since Java 8 there is a set of methods in the Math class: toIntExact(long) addExact(int,int) subtractExact(int,int) multiplyExact(int,int) …and versions for long as well. Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range. Example of addition: int x = … Read more

Binary String to Integer

You could use a Regex to check that it is “^[01]+$” (or better, “^[01]{1,32}$”), and then use Convert? of course, exceptions are unlikely to be a huge problem anyway! Inelegant? maybe. But they work. Example (formatted for vertical space): static readonly Regex binary = new Regex(“^[01]{1,32}$”, RegexOptions.Compiled); static void Main() { Test(“”); Test(“01101”); Test(“123”); Test(“0110101101010110101010101010001010100011010100101010”); … Read more