java 十进制转二进制
时间: 2023-11-10 20:57:08 浏览: 80
有多种方法可以在Java中将十进制数转换为二进制数。一种方法是使用Integer类的toString()方法,该方法接受两个参数:要转换的十进制数和基数。对于将十进制转换为二进制,我们可以将基数设置为2。下面是一个示例程序:
```java
import java.util.Scanner;
public class JavaD2B {
public static void main(String[] args) {
int number;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
number = sc.nextInt();
System.out.println("Binary number is " + Integer.toString(number, 2));
}
}
```
另一种方法是使用Integer类的toBinaryString()方法,该方法直接将十进制数转换为二进制数。下面是一个示例程序:
```java
import java.util.Scanner;
public class JavaD2B {
public static void main(String[] args) {
int number;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
number = sc.nextInt();
System.out.println("Binary number is " + Integer.toBinaryString(number));
}
}
```
如果你想了解更多关于十进制转二进制的方法,可以参考下面的示例程序。这个程序使用了辗转相除法来实现转换:
```java
import java.util.Scanner;
public class Number2Binary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Input a number: ");
int number = input.nextInt();
int number2;
// 如果是负数,需要加上2^31次方
if (number < 0) {
number2 = (int) (Math.pow(2, 31) + number);
} else {
number2 = number;
}
String binary = "";
// 通过辗转相除法,求出二进制数,保存在binary中
int shang = number2;
int yu;
int count = 0;
while (shang != 0) {
yu = shang % 2;
shang /= 2;
count++;
if (count % 4 == 0) {
binary = "_" + yu + binary;
} else {
binary = yu + binary;
}
}
// 不够32位,需要补齐
while (count < 31) {
count++;
if (count % 4 == 0) {
binary = "_" + 0 + binary;
} else {
binary = 0 + binary;
}
}
// 判断符号位
if (number < 0) {
binary = 1 + binary;
} else {
binary = 0 + binary;
}
System.out.println(binary);
}
}
}
```
阅读全文