Created
March 15, 2021 17:42
-
-
Save ChristopherDavenport/fa8a6e781ed84ca7493a326adf403f1e to your computer and use it in GitHub Desktop.
Translate Ints to and From Bit Positions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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