Skip to content

Instantly share code, notes, and snippets.

@LouisCAD
Last active December 24, 2022 16:28
Show Gist options
  • Save LouisCAD/04be811e22d45cbc7285ab247c6c12e7 to your computer and use it in GitHub Desktop.
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
@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()
@clslrns
Copy link

clslrns commented Aug 14, 2020

inline fun Int.hasFlag(flag: Int) = flag and this == flag

This is wrong, use flag or this == flag instead.

@LouisCAD
Copy link
Author

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

@clslrns
Copy link

clslrns commented Aug 17, 2020

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