Skip to content

Instantly share code, notes, and snippets.

@SleeplessByte
Created May 7, 2015 22:17
Show Gist options
  • Save SleeplessByte/e90da349d47baa310298 to your computer and use it in GitHub Desktop.
Save SleeplessByte/e90da349d47baa310298 to your computer and use it in GitHub Desktop.
Flag utilities for parcelable or packing/unpacking in general
public class FlagUtils {
/**
* Packs booleans into an integer
*
* This does not check if the number of booleans is less then the number of bits in the integer
*
* @param params the booleans
*
* @return the packed integer
*/
public static int pack( boolean... params ) {
int result = 0;
int flag = 0;
for ( boolean param : params )
{
result += param ? (1 << flag) : 0;
flag++;
}
return result;
}
/**
* Unpacks booleans from an integer
*
* This does not check if the count is less then the number of bits in the integer
*
* @param flags the packed integer
* @param count the number of packed booleans
*
* @return the booleans
*/
public static boolean[] unpack( int flags, int count ) {
boolean[] result = new boolean[count];
for ( int i = 0; i < count; i++ )
result[i] = isSet( flags, i );
return result;
}
/**
* Checks if a flag at position {@code flag} is set
*
* @param flags the packed integer
* @param flag the flag position
*
* @return true if it is
*/
public static boolean isSet( int flags, int flag ) {
int mask = (1 << flag);
return ( flags & mask ) == mask;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment