Answers for "Write a Java program to convert a Binary Number to Decimal and Decimal to Binary."

3

Java program to convert integer value into binary

import java.util.*;
import java.util.Scanner;
public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter the a number : ");
      num = sc.nextInt();
      // convert int to binary java
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}
Posted by: Guest on February-08-2021
0

binary to decimal in java program

public class Details {
 
  public int BinaryToDecimal(int binaryNumber){
 
    int decimal = 0;
    int p = 0;
    while(true){
      if(binaryNumber == 0){
        break;
      } else {
          int temp = binaryNumber%10;
          decimal += temp*Math.pow(2, p);
          binaryNumber = binaryNumber/10;
          p++;
       }
    }
    return decimal;
  }
 
  public static void main(String args[]){
    Details obj = new Details();
    System.out.println("110 --> "+obj.BinaryToDecimal(110));
    System.out.println("1101 --> "+obj.BinaryToDecimal(1101));
    System.out.println("100 --> "+obj.BinaryToDecimal(100));
    System.out.println("110111 --> "+obj.BinaryToDecimal(110111));
  }
}
Posted by: Guest on February-21-2021

Code answers related to "Write a Java program to convert a Binary Number to Decimal and Decimal to Binary."

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language