數組二進制輸出這裏是我的代碼:http://pastebin.com/x8XKSufP格式化從Java中
我需要的輸出格式轉換成適當的二進制格式。例如,如果你輸入一個小數點「64」,我需要它輸出「0100 0000」,而不是1000000.我一直試圖弄清楚這個問題一個多小時。請幫忙。
Test.java
import java.util.Scanner;
public class Test {
public static int[] getBinaryArray(int decimal) {
int result = decimal;
int length = 0;
while (result != 0) {
result /= 2;
length++;
}
return new int[length];
} // close getBinaryArray method
public static int[] decimalToBinary(int[] binary, int decimal) {
int result = decimal;
int arrayLength = binary.length - 1;
while (result != 0) {
if (result % 2 == 0) {
binary[arrayLength] = 0;
} else {
binary[arrayLength] = 1;
}
arrayLength--;
result /= 2;
} // close WHILE
return binary;
} // close decimalToBinary method
// Main method
public static void main(String[] args) {
// initialize the input scanner
Scanner input = new Scanner(System.in);
System.out.println("Enter a number in decimal format: ");
int getDecimal = input.nextInt();
int[] binary = decimalToBinary(getBinaryArray(getDecimal), getDecimal);
for (int i = 0; i < binary.length; i++) {
System.out.println(i + " " + binary[i]);
} // close FOR
} // main method
}
如果你的長度不是8的倍數,在前面加上足夠的「0',直到它。 –
而不是發佈鏈接到您的代碼,發佈代碼本身。由於這是你的第一個問題,所以我冒昧爲你做這件事。 –