在Java中格式化数组的二进制输出

时间:2011-11-06 02:18:01

标签: java

这是我的代码:http://pastebin.com/x8XKSufP

我需要将输出格式化为适当的二进制格式。例如,如果输入一个十进制“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
}

4 个答案:

答案 0 :(得分:0)

这不像Kal的解决方案那么干净,但它确实为你提供了每4位之间的空格。

import java.util.Scanner;

class decimalToBinaryConverter {

    public static void main(String[] args) {
        int groupsOf = 4; //Change this to 8 if you want bytes instead of half bytes.
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a number in decimal format: ");

        int myInt = input.nextInt(); //Max in put value is of course max integer value, 2,147,483,647.  Does not work with negative values.
        int bitCount = Integer.SIZE - Integer.numberOfLeadingZeros(myInt); //Determines at what position the leading bit is.
        int zerosNeeded = groupsOf - (bitCount % groupsOf); //Determines how many 0s need to be added to the bit group to ensure the group is full.
        StringBuilder tempSB = new StringBuilder();
        StringBuilder resultSB = new StringBuilder();

        while (zerosNeeded > 0 && zerosNeeded != groupsOf) {
            tempSB.append(0);
            zerosNeeded--;
        }

        tempSB.append(Integer.toBinaryString(myInt)); //At this point tempSB has the correct bits in the correct places, but with no spaces.

        for (int i = 0; i < tempSB.length(); i++) {
            if (i % groupsOf == 0) {
                resultSB.append(" "); //Put a space in between each bit group.
            }
            resultSB.append(tempSB.charAt(i));
        }
        System.out.println(resultSB.toString().trim()); //Trim the extra space off the front of resultSB and print it.
    }
}

答案 1 :(得分:0)

System.out.printf("%d%d%d%d %d%d%d%d", 
                (n&128)>0?1:0,
                 (n&64)>0?1:0, 
                 (n&32)>0?1:0, 
                 (n&16)>0?1:0,
                  (n&8)>0?1:0,
                  (n&4)>0?1:0, 
                  (n&2)>0?1:0, 
                   n&1) ;

......等等。

答案 2 :(得分:0)

转换为binaryString然后左边填充零应该可以解决问题。

这是一个简单的例子(不考虑大二进制字符串)

String s = Integer.toBinaryString(i);

int length = s.length();
int remainder = length % 8;
if ( remainder != 0 )
     length = length + (8 - remainder);

System.out.println(String.format("%0" + length + "d" , Integer.parseInt(s)));

答案 3 :(得分:0)

我不知道代码的“使用”,但这是我的解决方案(不要忘记导入java.io):

public static void main(String args[]) throws IOException {

    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the decimal value: ");
    String input = bf.readLine();

    // Parse the input
    int i = Integer.parseInt(input);

    String bin = null;
    String result = null;

    if ((Integer.toBinaryString(i).length() % 2) != 0) {
        bin = "0".concat(Integer.toBinaryString(i));
        // Formatting obtained binary
        result = (bin.substring(0, bin.length() / 2)).concat(" ").concat(
                bin.substring(bin.length() / 2, bin.length()));
    } else {
        bin = Integer.toBinaryString(i);
        //Formatting obtained binary
        result = (bin.substring(0, bin.length() / 2)).concat(" ").concat(
                bin.substring(bin.length() / 2, bin.length()));
    }

    System.out.println("Binary: " + result);
}

享受:)