https://kotlinlang.org logo
#announcements
Title
# announcements
k

karelpeeters

08/19/2019, 6:27 AM
BooleanArray(64) { (long shr it) and 1 != 0 }
l

LastExceed

08/19/2019, 6:28 AM
i see, and how would i convert back?
k

karelpeeters

08/19/2019, 6:31 AM
Hmm that's not quite as convenient, probably just a for loop is best.
You can also consider using a
BitSet
from Java, it can convert back and forth to a long array.
It's not actually that bad:
arr.foldIndexed(0L) { i, a, b -> a + if (b) 1 shr i else 0 }
l

LastExceed

08/19/2019, 6:37 AM
now you've lost me
k

karelpeeters

08/19/2019, 6:38 AM
Take a look at the source code of
fold
, it applies the lambda repeatedly to the previous result and the next element of the array. It's a common functional idiom, I'm sure there's lots of information about this online.
l

LastExceed

08/19/2019, 6:39 AM
ok ty
k

karelpeeters

08/19/2019, 6:39 AM
And in this case it basically ends up being
sumByLong
which is missing from the stdlib I think.
l

LastExceed

08/19/2019, 6:55 AM
hmm your code to convert back to Long always returns 1 but I can't find the bug
k

karelpeeters

08/19/2019, 6:56 AM
It has to be
shl
.
l

LastExceed

08/19/2019, 6:56 AM
ty
d

Dico

08/19/2019, 10:30 AM
You can also make your own class wrapping the long value with functions to set bits, if you're specifically looking for 64 values.
l

LastExceed

08/19/2019, 10:31 AM
could i make an inline class that uses [] syntax to access the individual bits? and yes i am specifically looking at
Long
values
r

Ruckus

08/19/2019, 2:04 PM
Not inline (you cannot mutate inline classes), but you can use
Copy code
class LongBit(private var bits: Long) {
    operator fun get(index: Int) = bits shr index and 1L != 0L
    operator fun set(index: Int, value: Boolean) {
        val mask = 1L shl index
        bits = if (value) bits or mask else bits and mask.inv()
    }
}
l

LastExceed

08/19/2019, 2:05 PM
thanks!
r

Ruckus

08/19/2019, 2:10 PM
Or you could just make some helper functions and use them on `Long`s directly
Copy code
fun Long.getBit(index: Int) = shr(index) and 1L != 0L
fun Long.withBit(index: Int, bit: Boolean): Long {
    val mask = 1L shl index
    return if (bit) or(mask) else and(mask.inv())
}
Heck, why not do both?
Copy code
fun Long.getBit(index: Int) = shr(index) and 1L != 0L
fun Long.withBit(index: Int, bit: Boolean): Long {
    val mask = 1L shl index
    return if (bit) or(mask) else and(mask.inv())
}

class LongBit(private var bits: Long) {
    operator fun get(index: Int) = bits.getBit(index)
    operator fun set(index: Int, bit: Boolean) {
        bits = bits.withBit(index, bit)
    }
    
    override fun toString() = bits.toULong().toString(2).padStart(64, '0')
}
4 Views