Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Code Optimization [java]

Name: Anonymous 2010-04-13 16:33

I'm working on a project that requires that I use processing. I am not too proficient with Java. I have written these retard-tier methods:


  color removeFromColor(int c, int subtraction)
  {
    for (int i = 16; i >= 0; i -= 8) {
      if ((c >> i & 0xFF) - subtraction > 0) {
        c |= (0 << i);
      } else {
        c -= (subtraction << i);
      }
    }
    return c;   
  }
 
  color addToColor(int c, int addition)
  {
    for (int i = 16; i >= 0; i -= 8) {
      if ((c >> i & 0xFF) + addition > 255) {
        c |= (255 << i);
      } else {
        c += (addition << i);
      }
    }
    return c;
  }


As you can perhaps guess, I would prefer if these methods were written as one private (factory?) method, with two wrapper methods for add and remove that modify the behavior of the main method. Unfortunately, I am not skilled enough to come up with an elegant solution. All of my design attempts thus far have resulted in overly-complicated, unnecessary bloat, or at least worse code than if I had just stuck to keeping two very-similar-yet-different methods.

Since in practice these are working just fine at the moment, I am asking this only out of curiosity. How would you optimize this? Or would you bother at all?

Name: Anonymous 2010-04-13 20:30

>>11
Alright, alright, shut up.  As this is Java you might as well make these static since they don't affect whatever this object is.  Secondly, how can the return type be declared "lowercase-color" but the actual return type an int?

static color modifyColor(int c, int mod)
{
   if(mod != 0)
   {
      int d = (mod > 0 ? 255 : 0);
      int i = 16;
      for(; i >= 0; i -= 8)
      {
         if((c >> i & 0xFF) + mod > d)
         {
            c |= (d << i);
         }
         else
         {
            c = (mod > 0 ? c + (mod << i) : c - (-mod << i));
         }
      }
   }
   return c;  
}


The only reason I used the ternary operation in the else case is because I can not remember if a negative number's two's complement is considered properly in this bitwise shift/addition statement.  I don't want to assume what you consider the correct output.  I'm assuming you already determined this is the case, however, since you are so confident that you did not check your input for its sign.  If not, then you can just use c += (modification << i);.

Further question: why do you want to make this class method private?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List