Question

Question is based on this site.

Could someone explain the meaning of these lines:

private int getBitValue(int n, int location) {
      int v = n & (int) Math.round(Math.pow(2, location));
      return v==0?0:1;
 }

and

private int setBitValue(int n, int location, int bit) {
    int toggle = (int) Math.pow(2, location), bv = getBitValue(n, location);
    if(bv == bit)
        return n;
    if(bv == 0 && bit == 1)
        n |= toggle;
    else if(bv == 1 && bit == 0)
        n ^= toggle;
    return n;
}
Was it helpful?

Solution

  int v = n & (int) Math.round(Math.pow(2, location));

Math.pow(2, location) raises 2 to the given power. This is rounded and converted to an integer. In binary, this will be 00000001 if location==0, 00000010 if location==1, 00000100 if location==2, etc. (Much better would be 1 << location which shifts a "1" by a certain number of bits, filling in 0 bits at the right. Using Math.pow will probably try to compute the logarithm of 2 every time it's called.)

n & ... is a bitwise AND. Since the item on the right has just one bit set, the effect is to zero out every bit in n except for that one bit, and put the result in v. This means that v will be 0 if that one bit is 0 in n, and something other than 0 if that bit is `, which means

  return v==0?0:1;

returns 0 if the bit is clear and 1 if it's set.

int toggle = (int) Math.pow(2, location), bv = getBitValue(n, location);

toggle is set to that Math.pow thing I already described. bv is set to the bit that's already in n, which is 0 or 1. If this equals the thing you're setting it to, then we don't need to do anything to n:

if(bv == bit)
    return n;

Otherwise, either we need to set it to 1 (remember that toggle will have just one bit set). n |= toggle is the same as n = n | toggle. | is a bit-wise OR, so that one bit will be set in n and all other bits in n will remain the same"

if(bv == 0 && bit == 1)
    n |= toggle;

Or we need to set the bit to 0. n ^= toggle is the same as n = n ^ toggle. n is an exclusive OR. If we get here, then the bit in n is 1, and the bit in toggle is 1, and we want to set the bit in n to 0, so exclusive OR will change that bit to 0 while leaving every other bit the same:

else if(bv == 1 && bit == 0)
    n ^= toggle;

OTHER TIPS

The getBitValue just gets the value of a specified bit (on a certain location)

The setBitValue sets the value of a bit on the matched specific location.

These getter/setter methods are usually used for image processing, i.e. if you have a musk and you want to change a specific bit value.

Nothing more or less.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top