I am trying to prepare for technical interviews and I noticed a few practice questions involved bit masking and bit shifting. I am unfamiliar with these concepts. I understand that if you are using half of a byte and want to leave the other half available you can mask the 4 bits you want to use, but I am still fairly confused about how this might be easily understood or applied to a coding problem. If someone has sufficient knowledge or some resource that explains this in very simple terms (preferably in Java) I would greatly appreciate it. Thanks!
Asked
Active
Viewed 109 times
-1
-
1For a concrete, real-world example (non java, usually), of a coding problem where they might be applied, it's no accident that the IP networking term "netmask" is called that. – Ian McLaird Feb 23 '15 at 23:06
2 Answers
0
Bitmasks are an effective tool if you have a collection of boolean flags, for which you'd like a compact representation, or if you want to be able to efficiently test for certain combinations of true/false patterns.
For example assume the following (C++, because my Java is quite rusty):
enum {
FlagOne = (1<<0),
FlagTwo = (1<<1),
FlagThree = (1<<2),
FlagFour = (1<<4),
FlagOneAndFour = FlagOne | FlagFour
};
unsigned int flags;
you can now do various tests in a very concise way. For example to test if any of FlagOne, FlagTwo or FlagFour are set you can write
if( 0 != (flags & (FlagOne | FlagTwo | FlatFour)) ) {
/*...*/
}
Or if you want to test for FlagOneAndFour being set you can do
if( FlagOneAndFour = (flags & FlagOneAndFour) ) {
/*...*/
}

datenwolf
- 159,371
- 13
- 185
- 298
0
Here are some examples:
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c ); // a & b = 12
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c ); // a | b = 61
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c ); // a ^ b = 49
c = ~a;/*-61 = 1100 0011 */
System.out.println("~a = " + c ); // ~a = -61
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c ); // a << 2 = 240
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c ); // a >> 2 = 15
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c ); // a >>> 2 = 15
But there is already a good and comprehensive SO question on bit operations in Java.

Community
- 1
- 1

Michael Dorner
- 17,587
- 13
- 87
- 117