Archived
1
0
Fork 0
This repository has been archived on 2025-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
uranos/blokk-api/src/main/kotlin/space/blokk/util/Bits.kt

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
}