37 lines
895 B
Kotlin
37 lines
895 B
Kotlin
package space.blokk.util
|
|
|
|
import kotlin.experimental.and
|
|
import kotlin.experimental.inv
|
|
import kotlin.experimental.or
|
|
|
|
/**
|
|
* Returns true if the bit at [index] is 1.
|
|
*/
|
|
fun Byte.checkBit(index: Int): Boolean {
|
|
val flag = (1 shl index).toByte()
|
|
return (this and flag) == flag
|
|
}
|
|
|
|
fun Byte.setBit(index: Int, value: Boolean): Byte {
|
|
val mask = (1 shl index).toByte()
|
|
return if (value) this or mask else this and mask.inv()
|
|
}
|
|
|
|
/**
|
|
* Returns true if the bit at [index] is 1.
|
|
*/
|
|
fun Int.checkBit(index: Int): Boolean {
|
|
val flag = 1 shl index
|
|
return (this and flag) == flag
|
|
}
|
|
|
|
fun Int.setBit(index: Int, value: Boolean): Int {
|
|
val mask = 1 shl index
|
|
return if (value) this or mask else this and mask.inv()
|
|
}
|
|
|
|
fun bitmask(vararg values: Boolean): Int {
|
|
var mask = 0
|
|
values.forEachIndexed { index, value -> mask = mask.setBit(index, value) }
|
|
return mask
|
|
}
|