Kotlinでビット操作を行うときのメモ。
よく使うビット操作をユーティリティメソッドとして以下にまとめました。
object BitwiseOperation {
fun getBit(num: Int, i: Int): Int =
(num and createMask(i, i)).countOneBits()
fun setBit(num: Int, i: Int): Int =
num or createMask(i, i)
fun clearBit(num: Int, i: Int): Int =
num and createMask(i, i, false)
fun updateBit(num: Int, i: Int, shouldSet: Boolean): Int =
if (shouldSet) setBit(num, i) else clearBit(num, i)
fun createMask(from: Int, to: Int, shouldSet: Boolean = true): Int {
require(from in 0 until Int.SIZE_BITS) { "from must be in the range of int bit size." }
require(to in 0 until Int.SIZE_BITS) { "to must be in the range of int bit size." }
require(from <= to) { "Incorrect indices combination. from: $from, to: $to" }
val mask = (allOneBits shl (to + 1)).inv() and (allOneBits shl from)
return if (shouldSet) mask else mask.inv()
}
fun getAllOneBits(): Int = allOneBits
private const val allOneBits: Int = 0.inv()
}