简体   繁体   中英

Binary Calculator

I am trying to create binary calculator that converts integers to 8 bit binary output. I am lost and any help would be appreciated. Here is my progress so far:

import java.util.Scanner;
import java.lang.Math;
public class Unit4 
{
    public static int convertToBinary(int baseTenIntOne)
    {
        int [] firstNum = new int [8];
        int binary = 0;
        int bvalue = 1;
        for (int i = 0; i < 8; i++)
        {
            if (baseTenIntOne % 2 == 1)
                binary += bvalue;
            else
                binary += 0;    
            bvalue *= 10;
        }
        System.out.println(binary);
        return binary;
    }
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);
        int baseTenIntOne;
        int baseTenIntTwo;
        System.out.println("Enter a base ten number between 0 and 255, inclusive.");
        baseTenIntOne = scan.nextInt();
        System.out.println(baseTenIntOne);
        System.out.println("Enter a base ten number between 0 and 255, inclusive.");
        baseTenIntTwo = scan.nextInt();
        System.out.println(baseTenIntTwo); 
        convertToBinary(baseTenIntOne);
    }   
}

You can put this snippet in your convertToBinary(int baseTenIntOne) method

{

if (baseTenIntOne == 0)
{

    return "0";
}

String binary = "";
while (baseTenIntOne > 0) {
    int rem = baseTenIntOne % 2;
    binary = rem + binary;
    baseTenIntOne = baseTenIntOne / 2;
}
System.out.println(binary);
return binary;

}

You can use the following method:

System.out.println("Enter a Integer Value:");
int h = Integer.parseInt(br.readLine());
String oct = Integer.toString(h,8);

Try using Integer.toBinaryString(int i);

And then append zeros to the beginning of the string

  public static String convertToBinary(int baseTenIntOne){
    String binaryRep = Integer.toBinaryString(baseTenIntOne);
    while(binaryRep.length()<8){
       binaryRep.insert(0, "0" );
    }

   return binaryRep;
  }

Forgotten was doing in the for-loop:

baseTenIntOne /= 2;

So the next bit appears at the first position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM