Last active
December 24, 2022 16:28
-
-
Save LouisCAD/04be811e22d45cbc7285ab247c6c12e7 to your computer and use it in GitHub Desktop.
Allows simple bit flags operation on int values in kotlin. Now available in Splitties: https://github.com/LouisCAD/Splitties/tree/master/modules/bitflags Inspired by: http://stackoverflow.com/a/40588216/4433326
This file contains 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
@file:Suppress("NOTHING_TO_INLINE") | |
import kotlin.experimental.and // Used for Byte | |
import kotlin.experimental.inv // Used for Byte | |
import kotlin.experimental.or // Used for Byte | |
inline fun Int.hasFlag(flag: Int) = flag and this == flag | |
inline fun Int.withFlag(flag: Int) = this or flag | |
inline fun Int.minusFlag(flag: Int) = this and flag.inv() | |
inline fun Byte.hasFlag(flag: Byte) = flag and this == flag | |
inline fun Byte.withFlag(flag: Byte) = this or flag | |
inline fun Byte.minusFlag(flag: Byte) = this and flag.inv() |
Actually, what you suggest is wrong @clslrns, just check it with a few actual bit flags and you'll see that the implementation in this gist is correct. BTW, this moved to a library: https://github.com/LouisCAD/Splitties/tree/master/modules/bitflags
Oh, sorry, I had an error during tests. Thanks for link and code!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is wrong, use
flag or this == flag
instead.