Binary to decimal Java converter

I'm creating a code that allows you to convert binary numbers to decimal numbers and vice versa I've created a code to convert decimal to binary, but I can't study how to implement binary to decimal

My decimal to binary code is as follows:

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 of how binary to decimal code works will also help

I've tried the least significant number * 1 method, then the next lowest * 1 * 2, then * 1 * 2 * 2, but I can't make it work

Thank you @ korhner. I use your number system and arrays and if statements

This is my work 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);

   }
}

Solution

Sample:

00000100

0 – 1 0 – 2 1 – 4 0 – 8 0 – 16 0 – 32 0 – 64 0 – 128

Sum value of bit 1 = 4

Good luck!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>