Skip to content

Instantly share code, notes, and snippets.

@ChristopherDavenport
Created March 15, 2021 17:42
Show Gist options
  • Save ChristopherDavenport/fa8a6e781ed84ca7493a326adf403f1e to your computer and use it in GitHub Desktop.
Save ChristopherDavenport/fa8a6e781ed84ca7493a326adf403f1e to your computer and use it in GitHub Desktop.
Translate Ints to and From Bit Positions
object BitInsanity {
def bitPositions(int: Int): List[Int] = {
val buffer = new scala.collection.mutable.ListBuffer[Int]()
var number = int
var position = 0
while (number != 0){
if ((number & 1) != 0) {
buffer.addOne(position)
}
position += 1
number = number >>> 1
}
buffer.toList
}
def fromBitPositions(l: List[Int]): Int = {
var x = 0x00
l.foreach{bitPosition =>
val mask = 1 << bitPosition
x = x | mask
}
x
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment