Created
February 28, 2020 22:56
-
-
Save kiwiandroiddev/234c871a91287f3a5d9ea2c46ba514c0 to your computer and use it in GitHub Desktop.
Kotlin function to convert a list of bits (booleans) with big-endian ordering to an integer
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
/** | |
* Converts a list of bits (booleans) with big-endian ordering to its corresponding | |
* integer. | |
*/ | |
fun List<Boolean>.bigEndianBitsToInt(): Int { | |
return reversed().foldIndexed(initial = 0) { bitNo: Int, output: Int, bit: Boolean -> | |
output or (bit.toInt() shl bitNo) | |
} | |
} | |
fun Boolean.toInt() = if (this) 1 else 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment