How to use Bitwise while setting properties
Bit manipulation to set multiple properties to a single field.

Search for a command to run...
Bit manipulation to set multiple properties to a single field.

No comments yet. Be the first to comment.
We all know, each component in Android has its lifecycle, be it Activity, Fragment or Service. Each component gets created and destroys (and a few other stages in between). To create a custom class that is lifecycle aware inherently, we can use a set...

hey, Android help me get data from my other app

Why Powermockito.whenNew() is not enough.

Post inspired by RecyclerCalendarAndroid Lib RecyclerView The theory is simple, we need each day of the calendar rendered as one cell of the RecyclerView. To achieve this, we need to first prepare list of all dates, but there is a problem, we are mi...

Sometimes we are faced with a situation, where a parameter can have multiple values, or even it can have combination of those values.
We have a few choices here, either we create multiple fields for each property, which is hard to scale but easier to understand.
Here is a code sample for that:
fun main() {
order(true, true, false)
}
fun order(hasOrderedCheeseBurger: Boolean, hasOrderedFries: Boolean, hasOrderedSoda: Boolean) {
println("Has Ordered CHEESEBURGER : ${hasOrderedCheeseBurger}"); // true
println("Has Ordered FRIES : ${hasOrderedFries}"); // true
println("Has Ordered SODA : ${hasOrderedSoda}"); // false
}
As you can see, we had to send 3 different parameters to know what this user had ordered and imagine, if, in future we need to add another item, let's say SANDWICH then we need to add another parameter.
Now, instead of passing multiple parameters, we can use bit manipulation to combine multiple parameters into a single parameter.
val CHEESEBURGER = 2; // 00000010
val FRIES = 4; // 00000100
val SODA = 8; // 00001000
fun main() {
val ordered = CHEESEBURGER or FRIES;
order(ordered)
}
fun order(what: Int) {
val hasOrderedCheeseBurger = what and CHEESEBURGER == CHEESEBURGER;
val hasOrderedFries = what and FRIES == FRIES;
val hasOrderedSoda = what and SODA == SODA;
println("Has Ordered CHEESEBURGER : ${hasOrderedCheeseBurger}"); // true
println("Has Ordered FRIES : ${hasOrderedFries}"); // true
println("Has Ordered SODA : ${hasOrderedSoda}"); // false
}
Here, bitwise allows us to add as many values as we need into a single parameter.