What does this statement mean? - java

Found it on this website.
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
I'M asking for the "position & 1 ..."
I've seen this statement several times, but never knew what it means :/ Though I guess its handy to know :P
Thanks!

& is the bitwise AND operator. Basically, (position & 1) is checking whether the least-significant bit of position is 1 or 0, which is a way of checking whether position is odd or even.
For a full run-down of Java operators, see e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html.

It is a bitwise AND of (the value of) position and 1.
So, if the least significant bit of position is 1 it will return 1, otherwise it returns 0.

The single & sign is a bitwise AND operation. You usually use them to apply a bit-mask. In this case if position's last (least significant) bit is 1 then (position & 1) == 1 will be true since the & 1 will zero everything except the last bit by "and-ing" each bit of 'position' with 1.

Related

Beginner explanation to Bitwise operands

I am currently taking Intro programming classes. We are learning Java SE (eventually moving up to Java EE). I have a grasp on most things, but I hit a wall with bitwise manipulation and masking. For example:
EDITED HERE:
I want to figure out if a number is divisible by 3 and 5, but not 2. The only requirements is that I can not use % to find the answer, it has to be in a method call, and I have to use masking and bitwise operands.
I already learned how to determine if a number is odd or even with this:
public static boolean isEven(int num) {
return ((num & 1) == 0);
}
I understand what the bitwise operands (&, |, ^, >> , <<) do but can't actually implement them properly. Our book also does not have information on this, it's from our teachers notes.
I'm not asking for just the answer, I need to understand how it actually works.
These are pretty tricky unless your prof has actually shown you how to do this sort of thing. I'll do 3, and you figure out how to do 5.
This works because 4 == 1 mod 3:
static boolean isDivisibleBy3(int n)
{
while(n<0 || n>3) {
n = (n&3) + (n>>2);
}
return (n==3 || n==0)
}
n&3 gets the lower two bits. (n>>2) gets the rest of the bits and divides by 4. Because 4 == 1 mod 3, dividing by 4 doesn't change the remainder mod 3. Then we add them back together and get a smaller number with the same remainder as the one we started with.
Repeat until we get a number less than 4. At that point it's not going to get any smaller.
There are faster ways to do this, but this way is the easiest to understand.

Check if only one single bit is set within an integer (whatever its position)

I store flags using bits within a 64-bits integer.
I want to know if there is a single bit set whatever the position within the 64-bits integer (e.i. I do not care about the position of any specific bit).
boolean isOneSingleBitSet (long integer64)
{
return ....;
}
I could count number of bits using the Bit Twiddling Hacks (by Sean Eron Anderson), but I am wondering what is the most efficient way to just detect whether one single bit is set...
I found some other related questions:
(8051) Check if a single bit is set
Detecting single one-bit streams within an integer
and also some Wikipedia pages:
Find first one
Bit manipulation
Hamming weight
NB: my application is in java, but I am curious about optimizations using other languages...
EDIT: Lưu Vĩnh Phúc pointed out that my first link within my question already got the answer: see section Determining if an integer is a power of 2 in the Bit Twiddling Hacks (by Sean Eron Anderson). I did not realized that one single bit was the same as power of two.
If you just literally want to check if one single bit is set, then you are essentially checking if the number is a power of 2. To do this you can do:
if ((number & (number-1)) == 0) ...
This will also count 0 as a power of 2, so you should check for the number not being 0 if that is important. So then:
if (number != 0 && (number & (number-1)) == 0) ...
(using x as the argument)
Detecting if at least one bit is set is easy:
return x!=0;
Likewise detecting if bit one (second lowest bit) is set is easy:
return (x&2)!=0;
Exactly one bit is set iff it is a power of two. This works:
return x!=0 && (x & (x-1))==0;
The wrapper class java.lang.Long has a static function bitCount() that returns the number of bits in a long (64-bit int):
boolean isSingleBitSet(long l)
{
return Long.bitCount(l) == 1;
}
Note that ints are 32-bit in java.
Assuming you have already an efficient - or hardware - implementation of ffs() - find first set - you may act as follows:
bool isOneSingleBitSet (long integer64)
{
return (integer64 >> ffs(integer64)) == 0;
}
The ffs() function may be already available, or you may like to see your own link above
lets assume X is a 64bit inter full of 0s exept the one you are looking for;
return ((64bitinteger&X)==X)
Seems like you can do a bitwise AND with a long representation of the single bit you want to check. For example, to check the LSB
return( (integer64 & 1L)!=0 );
Or to check the 4th bit from the right
return( (integer64 & 8L)!=0 );

implementing a patricia trie in java

I'm trying to rewrite a c++ patricia trie in java.
The c++ code is from here
full source code
I'm a bit stuck.
So here's my understanding:
#define ZEROTAB_SIZE 256
head->key = (char*)calloc(ZEROTAB_SIZE, 1);
we create an array of 256 bits for the key, so we can have a string with a maximum length of 32 characters and every character is represented with 8 bits. Can i implement this with a char array in java?
template <class T>
int PatriciaTrie<T>::bit_get(PatriciaTrieKey bit_stream, int n) {
if (n < 0) return 2; // "pseudo-bit" with a value of 2.
int k = (n & 0x7);
return ( (*(bit_stream + (n >> 3))) >> k) & 0x1;
}
k gets the last 7 bits of n, we move to the n/8 character of the string (not exactly n/8 since shifting to the right would remove anything lower than 8 to zero) then we shift the value of bit_stream[n>>3] by k and then we get last bit. if i use arrays in java could i rewrite this as
return (bit_stream[n>>3] >> k) & 0x1;
?
template <class T>
int PatriciaTrie<T>::bit_first_different(PatriciaTrieKey k1, PatriciaTrieKey k2) {
if (!k1 || !k2)
return 0; // First bit is different!
int n = 0;
int d = 0;
while ( (k1[n] == k2[n]) &&
(k1[n] != 0) &&
(k2[n] != 0) )
n++;
while (bit_get(&k1[n], d) == bit_get(&k2[n], d))
d++;
return ((n << 3) + d);
}
now this is where it gets confusing, the first part until the second while loop looks clear enough, loop and check how many bits are equal and non zero, but the i'm not sure what the second loop is doing, we take the address of the two keys and check the first bits if they're equal and if they are we check again until we find unequal bits?
Mainly i'm not sure how the address of the key is used here, but i might be confused on bit shifting in bit_get class too.
I want to do a comparison between there trie in c++ and java for my java class and i want to keep the implementations as similar as possible.
I'm not familiar with this data structure, but there are some problems with your understanding of this code.
First, calloc allocates 256 bytes, not bits. new byte[256] Would be comparable in java.
Second, n & 0x7 gets three bits of n, not seven. A clearer way to write this would be n/8 and n%8 instead of n>>3 and n & 7, but the bitwise operations might be slightly faster if your compiler is stupid.
You are correct that (bit_stream[n>>3]>>k) & 1 is the same.
Now, the first loop in bit_first_different loops over bytes, not bits. The check for 0 is to prevent running off the end of the keys. Once that loop terminates, n refers to the first differing byte. The second loop is then looking for which bit is different.
Note that if the two keys are not different, then the second loop may run off the end of the keys, potentially causing a segmentation fault.
Now, the & is taking the address of k1[n] because the bit_get function is expecting a pointer to a character...this passes in the nth element of the bit stream. After the loop, d is the offset of the first different bit of k[n].
Finally the code combines n (which byte?) With d (which bit in that byte?) to give the bit. Again I would advocate 8*n+d for clarity, but that's a matter of taste.
Can i implement this with a char array in java?
My java is a bit rusty but I believe char is signed in java which means that >> won't do what you expect it to. That's because shifting a signed number will not shift the sign bit so what you really want is the >>> operator or just use the byte type which is unsigned. I have a feeling that this is all kinds of wrong so please double-check.
return (bit_stream[n>>3] >> k) & 0x1;
In C or C++, *(array + k) is just another way to write array[k] so your translation looks correct. As for the interpretation, bit_stream[n>>3] essentially fetches the byte in which the desired bit is located. >> k Moves the desired bit in the least-significant bit position. Finally, we remove all the bits we're not interested in by masking them out with & 0x1. This leaves us with a value of either 0 or 1 depending on whether the bit was set or not.
What the final function does is compare 2 bit strings and returns the bit position where the 2 strings first differ. The first loop is essentially an optimized version of the second loop where instead of doing a bit by bit comparaison, it checks whole bytes instead.
In other words, it first loops over every bytes and find the first 2 that differ. It then takes those 2 differing bytes and loops over them until it finds the first 2 bit that differ. Note that the bit_get function is never going to receive an n greater 7 in this scenario because we know there's a difference somewhere in the byte. The final bit position is then constructed from the the result of both loops like so: (number_of_equal_bytes * 8) + number_of_equal_bits).

Exclusive or between N bit sets

I am implementing a program in Java using BitSets and I am stuck in the following operation:
Given N BitSets return a BitSet with 0 if there is more than 1 one in all the BitSets, and 1 otherwise
As an example, suppose we have this 3 sets:
10010
01011
00111
11100 expected result
For the following sets :
10010
01011
00111
10100
00101
01000 expected result
I am trying to do this exclusive with bit wise operations, and I have realized that what I need is literally the exclusive or between all the sets, but not in an iterative fashion,
so I am quite stumped with what to do. Is this even possible?
I wanted to avoid the costly solution of having to check each bit in each set, and keep a counter for each position...
Thanks for any help
Edit : as some people asked, this is part of a project I'm working on. I am building a time table generator and basically one of the soft constraints is that no student should have only 1 class in 1 day, so those Sets represent the attending students in each hour, and I want to filter the ones who have only 1 class.
You can do what you want with two values. One has the bits set at least once, the second has those set more than once. The combination can be used to determine those set once and no more.
int[] ints = {0b10010, 0b01011, 0b00111, 0b10100, 0b00101};
int setOnce = 0, setMore = 0;
for (int i : ints) {
setMore |= setOnce & i;
setOnce |= i;
}
int result = setOnce & ~setMore;
System.out.println(String.format("%5s", Integer.toBinaryString(result)).replace(' ', '0'));
prints
01000
Well first of all, you can't do this without checking every bit in each set. If you could solve this question without checking some arbitrary bit, then that would imply that there exist two solutions (i.e. two different ones for each of the two values that bit can be).
If you want a more efficient way of computing the XOR of multiple bit sets, I'd consider representing your sets as integers rather than with sets of individual bits. Then simply XOR the integers together to arrive at your answer. Otherwise, it seems to me that you would have to iterate through each bit, check its value, and compute the solution on your own (as you described in your question).

Extracting rightmost N bits of an integer

In the yester Code Jam Qualification round http://code.google.com/codejam/contest/dashboard?c=433101#s=a&a=0 , there was a problem called Snapper Chain. From the contest analysis I came to know the problem requires bit twiddling stuff like extracting the rightmost N bits of an integer and checking if they all are 1. I saw a contestant's(Eireksten) code which performed the said operation like below:
(((K&(1<<N)-1))==(1<<N)-1)
I couldn't understand how this works. What is the use of -1 there in the comparison?. If somebody can explain this, it would be very much useful for us rookies. Also, Any tips on identifying this sort of problems would be much appreciated. I used a naive algorithm to solve this problem and ended up solving only the smaller data set.(It took heck of a time to compile the larger data set which is required to be submitted within 8 minutes.). Thanks in advance.
Let's use N=3 as an example. In binary, 1<<3 == 0b1000. So 1<<3 - 1 == 0b111.
In general, 1<<N - 1 creates a number with N ones in binary form.
Let R = 1<<N-1. Then the expression becomes (K&R) == R. The K&R will extract the last N bits, for example:
101001010
& 111
————————————
000000010
(Recall that the bitwise-AND will return 1 in a digit, if and only if both operands have a 1 in that digit.)
The equality holds if and only if the last N bits are all 1. Thus the expression checks if K ends with N ones.
For example: N=3, K=101010
1. (1<<N) = 001000 (shift function)
2. (1<<N)-1 = 000111 (http://en.wikipedia.org/wiki/Two's_complement)
3. K&(1<<N)-1 = 0000010 (Bitmask)
4. K&(1<<N)-1 == (1<<N)-1) = (0000010 == 000111) = FALSE
I was working through the Snapper Chain problem and came here looking for an explanation on how the bit twiddling algorithm I came across in the solutions worked. I found some good info but it still took me a good while to figure it out for myself, being a bitwise noob.
Here's my attempt at explaining the algorithm and how to come up with it. If we enumerate all the possible power and ON/OFF states for each snapper in a chain, we see a pattern. Given the test case N=3, K=7 (3 snappers, 7 snaps), we show the power and ON/OFF states for each snapper for every kth snap:
1 2 3
0b:1 1 1.1 1.0 0.0 -> ON for n=1
0b:10 2 1.0 0.1 0.0
0b:11 3 1.1 1.1 1.0 -> ON for n=1, n=2
0b:100 4 1.0 0.0 1.0
0b:101 5 1.1 1.0 1.0 -> ON for n=1
0b:110 6 1.0 0.1 0.1
0b:111 7 1.1 1.1 1.1 -> ON for n=2, n=3
The lightbulb is on when all snappers are on and receiving power, or when we have a kth snap resulting in n 1s. Even more simply, the bulb is on when all of the snappers are ON, since they all must be receiving power to be ON (and hence the bulb). This means for every k snaps, we need n 1s.
Further, you can note that k is all binary 1s not only for k=7 that satisfies n=3, but for k=3 that satisifes n=2 and k=1 that satisifes n=1. Further, for n = 1 or 2 we see that every number of snaps that turns the bulb on, the last n digits of k are always 1. We can attempt to generalize that all ks that satisfy n snappers will be a binary number ending in n digits of 1.
We can use the expression noted by an earlier poster than 1 << n - 1 always gives us n binary digits of 1, or in this case, 1 << 3 - 1 = 0b111. If we treat our chain of n snappers as a binary number where each digit represents on/off, and we want n digits of one, this gives us our representation.
Now we want to find those cases where 1 << n - 1 is equal to some k that ends in n binary digits of 1, which we do by performing a bitwise-and: k & (1 << n - 1) to get the last n digits of k, and then comparing that to 1 << n - 1.
I suppose this type of thinking comes more naturally after working with these types of problems a lot, but it's still intimidating to me and I doubt I would ever have come up with such a solution by myself!
Here's my solution in perl:
$tests = <>;
for (1..$tests) {
($n, $k) = split / /, <>;
$m = 1 << $n - 1;
printf "Case #%d: %s\n", $_, (($k & $m) == $m) ? 'ON' : 'OFF';
}
I think we can recognize this kind of problem by calculating the answer by hand first, for some series of N (for example 1,2,3,..). After that, we will recognize the state change and then write a function to automate the process (first function). Run the program for some inputs, and notice the pattern.
When we get the pattern, write the function representing the pattern (second function), and compare the output of the first function and the second function.
For the Code Jam case, we can run both function against the small dataset, and verify the output. If it is identical, we have a high probability that the second function can solve the large dataset in time.

Categories