Skip to content

Instantly share code, notes, and snippets.

@leshchenko
Created July 29, 2019 08:26
Show Gist options
  • Save leshchenko/72765ae127e721d3a47303aaa46fa1e3 to your computer and use it in GitHub Desktop.
Save leshchenko/72765ae127e721d3a47303aaa46fa1e3 to your computer and use it in GitHub Desktop.
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