Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get binary representation of Int in Kotlin

Tags:

binary

kotlin

bit

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

like image 266
Rashi Karanpuria Avatar asked May 04 '18 10:05

Rashi Karanpuria


People also ask

How do you int in Kotlin?

To convert a string to integer in Kotlin, use String. toInt() or Integer. parseInt() method. If the string can be converted to a valid integer, either of the methods returns int value.


2 Answers

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.

like image 61
Rashi Karanpuria Avatar answered Sep 29 '22 04:09

Rashi Karanpuria


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) 
like image 40
Ilya Avatar answered Sep 29 '22 02:09

Ilya