返回目录
将10进制数转为2进制(16位),每4个二进制数空1格,不足的位数补0
Python源码
import java.util.Scanner;
public class BinaryConverter {
public static void main(String[] args) {
System.out.print("请输入一个整数:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
int[] binaryArray = convertToBinary(n);
printBinaryArray(binaryArray);
}
// 将整数转换为二进制数组
public static int[] convertToBinary(int n) {
int[] binaryArray = new int[16];
int m = n;
int k = binaryArray.length - 1;
do {
binaryArray[k] = m % 2;
m /= 2;
k--;
} while (m != 0);
return binaryArray;
}
// 打印二进制数组,每4个二进制数空一格
public static void printBinaryArray(int[] binaryArray) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < binaryArray.length; i++) {
stringBuilder.append(binaryArray[i]);
if ((i + 1) % 4 == 0 && i != binaryArray.length - 1) {
stringBuilder.append(" ");
}
}
System.out.println("二进制表示为:" + stringBuilder.toString());
}
}
C语言源码
#include <stdio.h>
// 将整数转换为二进制数组
void convertToBinary(int n, int binaryArray[]) {
int m = n;
int k = 15;
do {
binaryArray[k] = m % 2;
m /= 2;
k--;
} while (m != 0);
}
// 打印二进制数组,每4个二进制数空一格
void printBinaryArray(int binaryArray[]) {
for (int i = 0; i < 16; i++) {
printf("%d", binaryArray[i]);
if ((i + 1) % 4 == 0 && i != 15) {
printf(" ");
}
}
printf("\n");
}
int main() {
printf("请输入一个整数:");
int n;
scanf("%d", &n);
int binaryArray[16];
convertToBinary(n, binaryArray);
printf("二进制表示为:");
printBinaryArray(binaryArray);
return 0;
}
Java源码
import java.util.Scanner;
public class BinaryConverter {
// 将整数转换为二进制数组
public static void convertToBinary(int n, int[] binaryArray) {
int m = n;
int k = 15;
do {
binaryArray[k] = m % 2;
m /= 2;
k--;
} while (m != 0);
}
// 打印二进制数组,每4个二进制数空一格
public static void printBinaryArray(int[] binaryArray) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 16; i++) {
stringBuilder.append(binaryArray[i]);
if ((i + 1) % 4 == 0 && i != 15) {
stringBuilder.append(" ");
}
}
System.out.println("二进制表示为:" + stringBuilder.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int n = scanner.nextInt();
scanner.close();
int[] binaryArray = new int[16];
convertToBinary(n, binaryArray);
printBinaryArray(binaryArray);
}
}
1 条评论
[...]序号题目1父母小于等于n的最简真分数2大于n的最小回文素数3多个数的最小公倍数4多个数的最大公约数5文件单词统计610进制数转2进制[...]