import structure5.*; import java.util.Iterator; public class BIterator extends AbstractIterator { // n is the number whose bits I want to iterate through protected int n; // current keeps track of the "next bit" to yield. // In java, ints have 32 bits, so we can continue to yield // new bits as long as 0 <= current < 32 protected int current; public BIterator(int n) { // store our value, then "reset" our iteration // back to the first bit (current = 0) this.n = n; reset(); } public void reset() { current = 0; } /** * This organization lets us reuse code: * - get() extracts the current value * - the rest of "next" advances the iteration */ public String next() { String nextBit = get(); current++; return nextBit; } /** * Since an int has 32 bits, we can only call next() * 32 times. (Each next call advances current by 1) */ public boolean hasNext() { return current < 32; } /** * Strategy: construct a "mask" in order to isolate the bit * value at the target position. * * Then we either yield a "0" or a "1", depending on the * target bit's value. */ public String get() { // shift a `1` by `current` places to the left so we can // "extract" the target bit. For example: // 1 << 0 = 000...0001 (in binary) // 1 << 1 = 000...0010 (in binary) // 1 << 2 = 000...0100 (in binary) // etc. // whichBit stores the "mask" we will use to extract // the bit int whichBit = 1 << current; // Since `whichBit` has a 1 in exactly one bit position, // the expression (n & whichBit) will isolate that bit // from our original int `n`. // In other words, if `n` had a 1 at that position, the result // will have a 1 at that bit position and 0 everywhere else. // If `n` had a 0 at that bit position, then the result will // be all 0's. So we compare the "masked" value to the "mask"; // if they match, then we know we had a 1 at that position! boolean isOne = (n & whichBit) == whichBit; return isOne ? "1" : "0"; } }