Binary to Decimal Java converter
java
Solution
sample:
00000100
0 - 1 0 - 2 1 - 4 0 - 8 0 - 16 0 - 32 0 - 64 0 - 128
Sum values with bit 1 = 4
Good luck!
Problem
I am creating a code that allows you to convert a binary number to a decimal number and vice versa. I have created a code that converts decimal to binary but can not workout how to implement the binary to decimal aspect. My code for decimal to binary is below: ``` import java.util.*; public class decimalToBinaryTest { public static void main (String [] args) { int n; Scanner in = new Scanner(System.in); System.out.println("Enter a positive interger"); n=in.nextInt(); if(n < 0) { System.out.println("Not a positive interger"); } else { System.out.print("Convert to binary is: "); binaryform(n); } } private static Object binaryform(int number) { int remainder; if(number <= 1) { System.out.print(number); return " "; } remainder= number % 2; binaryform(number >> 1); System.out.print(remainder); { return " "; } } } ``` An explanation to how the binary to decimal code work would help as well. I have tried the method of the least significant `digit*1` then the next least `*1*2` then `*1*2*2` but can not get it to work. Thank you @korhner I used your number system with arrays and if statements. This is my working code: ``` import java.util.*; public class binaryToDecimalConvertor { public static void main (String [] args) { int [] positionNumsArr= {1,2,4,8,16,32,64,128}; int[] numberSplit = new int [8]; Scanner scanNum = new Scanner(System.in); int count1=0; int decimalValue=0; System.out.println("Please enter a positive binary number.(Only 1s and 0s)"); int number = scanNum.nextInt(); while (number > 0) { numberSplit[count1]=( number % 10); if(numberSplit[count1]!=1 && numberSplit[count1] !=0) { System.out.println("Was not made of only \"1\" or \"0\" The program will now restart"); main(null); } count1++; number = number / 10; } for(int count2 = 0;count2<8;count2++) { if(numberSplit[count2]==1) { decimalValue=decimalValue+positionNumsArr[count2]; } } System.out.print(decimalValue); } } ```