在 Java 中将 Int 转换为二进制
-
在 Java 中使用
Integer.toBinaryString()将 Int 转换为二进制 -
在 Java 中使用
Integer.toString()将 Int 转换为二进制 -
在 Java 中使用
StringBuilder和一个循环将 Int 转换为二进制
二进制数用两个二进制数字表示,即 0 和 1。我们可以使用下面列出的三种方法将 int 值转换为 Java 中的二进制值。
在 Java 中使用 Integer.toBinaryString() 将 Int 转换为二进制
将 int 值转换为二进制的最常见和最简单的方法是使用 Integer 类的 toBinaryString() 函数。Integer.toBinaryString() 采用 int 类型的参数。
在程序中,我们将一个 int 值存储在变量 numInt 中,然后将其作为参数传递给返回 String 的 Integer.toBinaryString() 方法。
public class JavaExample {
public static void main(String[] args) {
int numInt = 150;
String binaryString = Integer.toBinaryString(numInt);
System.out.println(binaryString);
}
}
输出:
10010110
在 Java 中使用 Integer.toString() 将 Int 转换为二进制
在这个例子中,我们使用 Integer 类方法的另一个方法:toString() 方法。
Integer.toString() 接受两个参数,其中第二个参数是可选的。第一个参数是要转换为字符串的值,第二个参数是要转换的基数值。
对于我们的程序,我们需要使用 toString() 函数的两个参数来指定基数 2,表示二进制数字 0 和 1。简单来说,当我们使用基数 2 时,int 被转换为仅代表 0 和 1 的 String 值。
我们打印出 numInt 的二进制表示的结果。
public class JavaExample {
public static void main(String[] args) {
int numInt = 200;
String binaryString = Integer.toString(numInt, 2);
System.out.println(binaryString);
}
}
输出:
11001000
在 Java 中使用 StringBuilder 和一个循环将 Int 转换为二进制
最后一个程序采用传统方法;我们没有使用内置函数将 int 值转换为二进制,而是创建了执行相同工作的函数。
在下面的代码中,我们创建了一个函数 convertIntToBinary(),它接收 int 值作为要转换的参数。我们将函数的返回类型设置为字符串。
在 convertIntToBinary() 方法中,我们首先检查 int 变量 numInt 是否保持零。如果是,我们返回 0,因为 int 中 0 的二进制表示也是 0。如果它是一个非零整数值,我们创建一个 StringBuilder 类和一个 while 循环。
我们运行循环直到 numInt 大于零。在循环中,我们执行三个步骤;第一种是使用 numInt % 2 找到 numInt 的余数,然后将 remainder 的值附加到 StringBuilder。
最后一步,我们将 numInt 值除以 2 并将其存储在 numInt 本身中。一旦我们执行完所有步骤并退出循环,我们反转 stringBuilder 值以获得正确的结果并在将 stringBuilder 值转换为 String 后返回结果。
在 main() 方法中,我们获取用户的输入并将其传递给返回二进制结果的 convertIntToBinary() 方法。
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
System.out.println("Enter a number to convert it to a binary: ");
Scanner scanner = new Scanner(System.in);
int getIntNum = scanner.nextInt();
String getConvertedResult = convertIntToBinary(getIntNum);
System.out.println("Converted Binary: " + getConvertedResult);
}
static String convertIntToBinary(int numInt) {
if (numInt == 0)
return "0";
StringBuilder stringBuilder = new StringBuilder();
while (numInt > 0) {
int remainder = numInt % 2;
stringBuilder.append(remainder);
numInt /= 2;
}
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
}
输出:
Enter a number to convert it to a binary:
150
Converted Binary: 10010110
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn