Search code examples
javabinarynumbersshort

Java, print a short as binary with all 16 bits


For example:

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

I tried using Integer.toBinaryString() but that prints

10 -> 1010
15 -> 1111

Is there a function that can print the short with all 16 digits or do I have to write my own.


Solution

  • You could pad the left side with 0s:

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