55

Is there a method that can be used to get an Integer's representation in bits? For example when provided: 0 gives 0 4 gives 100 22 gives 10110

Rashi Karanpuria
  • 1,605
  • 1
  • 11
  • 18

6 Answers6

71

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.

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
Rashi Karanpuria
  • 1,605
  • 1
  • 11
  • 18
  • 5
    Beware negative numbers though. `(-2).toString(2)` will be `-10` instead of `11111111111111111111111111111110`. So you get the number in [base-2 numeral system](https://en.wikipedia.org/wiki/Binary_number) rather than its [2-complement](https://en.wikipedia.org/wiki/Two%27s_complement) bit representation. – Ilya May 05 '18 at 04:10
  • 1
    @ilya How do we deal with negative Ints then? – Rashi Karanpuria May 05 '18 at 07:15
  • @RashiKaranpuria you have to interpret that info using the negative sign in the string representation. Since 2's complement is not available(at least right now) there is no other way of cleanly managing that in my opinion. llya correct me if I missed something. (I am new to Kotlin, might have missed the fine print somewhere) – phoenix Jul 30 '18 at 15:57
  • 1
    If you want leading zeros: `Integer.toBinaryString(1).padStart(Int.SIZE_BITS, '0')` (added an answer with more details). – Adam Millerchip Oct 02 '20 at 07:55
  • @RashiKaranpuria To get 2-complement representation you could perform `a.xor(4294967295)` where `4294967295` is the number where all the bits are 1 (i.e. 1111...1) – Albert Bikeev Mar 28 '22 at 18:06
34

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)
Ilya
  • 21,871
  • 8
  • 73
  • 92
13

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')
        }
}
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
3

I'm using this method to convert integer to binary,

fun Int.toBinary(len: Int): String {
    return String.format("%" + len + "s", this.toString(2)).replace(" ".toRegex(), "0")
}

Call this method like this, numberToBeConvert.toBinary(length)

4.toBinary(8) = 00000100
khaleel_jageer
  • 1,404
  • 4
  • 16
  • 37
1

If you want to use pure Kotlin and binary representation must have a fixed length. For example, if you want to get 00111111 (63) you can do it like this:

fun UByte.toBinary(): String {
    return buildString(8) {
        val binaryStr = this@toBinary.toString(2)
        val countOfLeadingZeros = 8 - binaryStr.count()
        repeat(countOfLeadingZeros) {
            append(0)
        }
        append(binaryStr)
    }
}

You may modify that code to use it with UInt. However, make sure you use it with an unsigned type.

Ninjaval
  • 113
  • 1
  • 5
0

If you have bigger numbers than Integer, you can use BigInteger.

val binaryString = BigInteger("12345678987654321").toString(2)
Heinrisch
  • 5,835
  • 4
  • 33
  • 43