[英]Binary Calculator
I am trying to create binary calculator that converts integers to 8 bit binary output. 我正在尝试创建将整数转换为8位二进制输出的二进制计算器。 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 您可以将此代码段放入您的convertToBinary(int baseTenIntOne)方法中
{ {
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);
尝试使用
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: 被遗忘的是在for循环中做的:
baseTenIntOne /= 2;
So the next bit appears at the first position. 因此,下一位出现在第一个位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.