How to get binary representation of Int in Kotlin

I wanted a function that prints out the 32-bit binary representation of all the bits of the integer. The standard library functions mentioned in the other answers do not do this. However, it can be done by combining Integer.toBinaryString() as Rashi Karanpuria pointed out with the Kotlin stdlib function padStart():

fun Int.to32bitString(): String =
    Integer.toBinaryString(this).padStart(Int.SIZE_BITS, '0')

fun main() {
    println(Int.MIN_VALUE.to32bitString())
    println((-1).to32bitString())
    println(0.to32bitString())
    println(1.to32bitString())
    println(Int.MAX_VALUE.to32bitString())
}

Output:

10000000000000000000000000000000
11111111111111111111111111111111
00000000000000000000000000000000
00000000000000000000000000000001
01111111111111111111111111111111

An equivalent method if you don't have access to Integer.toBinaryString(): Int.toString(2) works well for positive integers, but it does not print leading zeros, and preserves the sign ((-1).toString(2) returns "-1" instead of a string of 1 bits). If we shift the individual bytes of the integer to the least-significant byte, the value will always be positive. We can use Int.toString(2) to get a representation of each byte individually, then join them back together (works for Long too):

fun Int.toBinaryString(): String = let { int ->
    IntProgression
        .fromClosedRange(rangeStart = Int.SIZE_BITS - 8, rangeEnd = 0, step = -8)
        .joinToString("") { bytePos ->
            (int shr bytePos and 0xFF).toString(2).padStart(8, '0')
        }
}

Starting with Kotlin 1.3 the binary representation of a signed integer can be obtained by reinterpreting it as an unsigned one and converting it to string base 2:

a.toUInt().toString(radix = 2)

Method 1: Use Integer.toBinaryString(a) where a is an Int. This method is from the Java platform and can be used in Kotlin. Find more about this method at https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int)

Note: This method works for both positive and negative integers.

Method 2: Use a.toString(2) where a is an Int, 2 is the radix Note: This method only works for positive integers.

Tags:

Binary

Bit

Kotlin