介绍
在本实验中,我们将学习如何在 Java 中将整数转换为二进制数。有多种方法可以实现这种转换,我们将介绍最常用的几种方法。
在本实验中,我们将学习如何在 Java 中将整数转换为二进制数。有多种方法可以实现这种转换,我们将介绍最常用的几种方法。
toBinaryString()
方法是将整数转换为二进制字符串的最简单方式。该方法是 Integer
类的一个方法,在将 int
转换为二进制后返回一个字符串。
public static String toBinaryString(int val)
这里的 val
是我们想要转换为二进制数制的值。该方法将以字符串格式返回二进制值。
public class IntegerToBinaryConverter {
public static void main(String[] args) {
int val = 183;
System.out.println("Value in binary system is: " + Integer.toBinaryString(val));
}
}
输出:Value in binary system is: 10110111
这种方法完全基于数学原理。我们通过考虑 32 位二进制表示,声明一个大小为 32 的整数数组。每次我们将数字除以 2,并将余数存储在整数数组中。最后,为了得到结果,我们以相反的顺序遍历数组。
public class IntegerToBinaryConverter {
public static void main(String[] args) {
int val = 183;
int num[] = new int[32];
int pos = 0;
while (val > 0) {
num[pos++] = val % 2;
val = val / 2;
}
System.out.print("Value in binary system is: ");
for (int i = pos - 1; i >= 0; i--) {
System.out.print(num[i]);
}
}
}
输出:Value in binary system is: 10110111
通过使用右移运算符,我们可以将任何值减半,由于我们在位级别操作,这是一种非常低成本的运算;其余部分与上述示例中提到的内容相同。最后,我们通过反转存储在 StringBuilder
对象中的值来打印二进制形式的结果。
public class IntegerToBinaryConverter {
public static void main(String[] args) {
int val = 183;
StringBuilder binary = new StringBuilder(32);
while (val > 0) {
binary.append(val % 2);
val >>= 1;
}
binary.reverse().toString();
System.out.print("Value in binary system is: " + binary.reverse().toString());
}
}
输出:Value in binary system is: 10110111
在 java.lang.Integer
类中,还有一种有趣的方式是使用 Integer.toString()
方法。该方法接受第一个参数作为数字,第二个参数作为基数(基数表示数制的进制),例如 2 表示二进制,8 表示八进制,16 表示十六进制;在我们的例子中,我们将基数设置为 2 以表示二进制数。
public class IntegerToBinaryConverter {
public static void main(String[] args) {
int val = 183;
System.out.print("Value in binary system is: " + Integer.toString(val, 2));
}
}
输出:Value in binary system is: 10110111
在本实验中,我们学习了如何使用四种不同的方法在 Java 中将整数转换为二进制数制。第一种方法是使用内置的 toBinaryString()
方法,第二种方法是使用长除法,第三种方法是使用位操作,第四种方法是使用 Integer.toString()
方法。
每种方法都有其优缺点,你可以根据需求选择最适合的方法。