Java,打印所有16位的二进制短

时间:2015-07-20 18:09:33

标签: java binary numbers short

例如:

10 - > 0000 0000 0000 1010
15 - > 0000 0000 0000 1111

我尝试使用Integer.toBinaryString(),但打印

10 - > 1010
15 - > 1111

是否有一个功能可以打印所有16位数的短信,或者我必须自己编写。

4 个答案:

答案 0 :(得分:8)

您可以在左侧填充0:

int x=10;//or whatever
String.format("%016d", Integer.parseInt(Integer.toBinaryString(x)));

答案 1 :(得分:0)

附加手册0可能有帮助

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

将生成0000000000000001

答案 2 :(得分:0)

您还可以使用以下技巧来显示前导zero/s。有关详细信息,请查看this thread

int displayMask = 1 << (size - 1);
StringBuffer buf = new StringBuffer( size);
for ( int c = 1; c <= size; c++ ) 
{
    buf.append( ( value & displayMask ) == 0 ? '0' : '1' );
    value <<= 1;
}

根据this answer Integer.toBinaryString()仅针对Integer / int引导zeros。它不适用于byte

答案 3 :(得分:0)

您可以使用String.format()在结果前添加填充。填充必须是空格,因为Integer.toBinaryString()返回String。然后你需要做的就是用零(0)替换空格并分割每个半字节(第四位)。

import java.util.*;

public class BinaryNumberPrinter {
  public static void main(String[] args) {
    int[] numbers = { 10, 15 };

    for (int number : numbers) {
      String binaryValue = join(splitEveryFour(toShortBinary(number)), " ");
      System.out.printf("%d -> %s%n", number, binaryValue);
    }
  }

  public static String toShortBinary(int value) {
    return String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0');
  }

  public static List<String> splitEveryFour(String value) {
    return Arrays.asList(value.split("(?<=\\G....)"));
  }

  public static String join(Iterable<? extends CharSequence> s, String delimiter) {
    Iterator<? extends CharSequence> iter = s.iterator();
    if (!iter.hasNext()) return "";
    StringBuilder buff = new StringBuilder(iter.next());
    while (iter.hasNext()) buff.append(delimiter).append(iter.next());
    return buff.toString();
  }
}

预期产出:

10 -> 0000 0000 0000 1010
15 -> 0000 0000 0000 1111