Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bitmask filtering
class Bitmask(
mask: Int
) {
private var bitmask = mask
val mask: Int
get() = bitmask
constructor() : this(0)
constructor(vararg values: Pair<Int, Boolean>) : this(0) {
values.forEach { (flag, value) ->
set(flag, value)
}
}
operator fun get(flag: Int): Boolean = mask.and(flag) != 0
operator fun set(flag: Int, value: Boolean) {
bitmask = if (value) {
bitmask.or(flag)
} else {
bitmask.and(flag.inv())
}
}
override fun toString(): String {
val mask = bitmask.toString(2)
return "Mask: $mask\nValues:\n" + mask
.reversed()
.toCharArray()
.mapIndexed { i, value ->
String.format("\t%1$3d -> %2\$s", Math.pow(2.0, i.toDouble()).toInt(), value != '0')
}.joinToString(separator = "\n")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Bitmask
if (bitmask != other.bitmask) return false
return true
}
override fun hashCode(): Int {
return bitmask
}
companion object {
fun parse(obj: Any?) = Bitmask(when (obj) {
is Int -> obj
is Long -> obj.toInt()
is String -> obj.toIntOrNull() ?: 0
else -> 0
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.