Skip to content

Instantly share code, notes, and snippets.

@oguna
Created February 7, 2016 13:56
Show Gist options
  • Select an option

  • Save oguna/326d595289672cb60f1f to your computer and use it in GitHub Desktop.

Select an option

Save oguna/326d595289672cb60f1f to your computer and use it in GitHub Desktop.
ScalaのInt型でビットを扱う
object BitVal {
implicit class BitInt(val self: Int) extends AnyVal {
@inline
def on(place: Int): Int = self | (1 << place)
@inline
def off(place: Int): Int = self & ~(1 << place)
@inline
def countOn(): Int = {
var count = 0
var _self = self
while (_self > 0) {
count += _self & 1
_self >>= 1
}
count
}
@inline
def countOff(): Int = 32 - countOn()
@inline
def toBitString(): String = {
val sb = new StringBuilder()
sb.append("0b")
for (figure <- 31 to 0 by -1) {
val bitChar = self & 1 << figure match {
case 0 => '0'
case _ => '1'
}
sb.append(bitChar)
}
sb.toString()
}
}
def main(args: Array[String]): Unit = {
val a = 1234
assert(a.on(2) == 1238)
assert(a == a.on(2).off(2))
assert(a.countOn() == 5)
assert(a.countOff() == 27)
assert(a.toBitString() == "0b00000000000000000000010011010010")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment