Java Online Compiler
Example: Binary to Decimal Converter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Binary to Decimal Converter import java.util.Scanner; public class Main { /** * Converts a binary string to its decimal equivalent. * @param binaryString The binary number as a string. * @return The decimal equivalent of the binary string. */ public static int binaryToDecimal(String binaryString) { int decimal = 0; int power = 0; // Represents 2^0, 2^1, 2^2, ... // Iterate through the binary string from right to left for (int i = binaryString.length() - 1; i >= 0; i--) { char bit = binaryString.charAt(i); // If the bit is '1', add 2^power to the decimal number if (bit == '1') { decimal += Math.pow(2, power); } power++; // Increment power for the next bit } return decimal; } public static void main(String[] args) { // Example usage String binary = "1011"; int decimalResult = binaryToDecimal(binary); System.out.println("Binary: " + binary + " -> Decimal: " + decimalResult); // Output: 11 } }
Output
Clear
ADVERTISEMENTS