How to convert a Binary String to a base 10 integer in Java
You need to specify the radix. There’s an overload of Integer#parseInt() which allows you to. int foo = Integer.parseInt(“1001”, 2);
You need to specify the radix. There’s an overload of Integer#parseInt() which allows you to. int foo = Integer.parseInt(“1001”, 2);
This is something people trip over all the time, even when they know about it. 🙂 You’re seeing this for the same reason parseInt(“1abc”) returns 1: parseInt stops at the first invalid character and returns whatever it has at that point. If there are no valid characters to parse, it returns NaN. parseInt(8, 3) means … Read more
Surprisingly, people were giving only solutions that convert to small bases (smaller than the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity. So here is a super simple solution: def numberToBase(n, b): if n == 0: return [0] digits = … Read more
It always a good practice to pass radix with parseInt – parseInt(string, radix) For decimal – parseInt(id.substring(id.length – 1), 10) If the radix parameter is omitted, JavaScript assumes the following: If the string begins with “0x”, the radix is 16 (hexadecimal) If the string begins with “0”, the radix is 8 (octal). This feature is … Read more