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-14 2:22

>>13
All numeric primitives in Java are signed.  As far as I can tell, there's no way to change this. Except through effort.
http://darksleep.com/player/JavaAndUnsignedTypes.html

I submit version two:
int x = (d == 0 ? -1 : 1);
if( ((c >> i & 0xFF) + mod)*x > d)

If mod is positive, then addition and 256 > 255 is true if the addition goes over; if mod is negative, then subtraction and 1 > 0 is true if the subtraction goes under.  It does create one more conditional to evaluate but it saves on branching the whole method into two ifs.

If you want the positive constants for addition and subtraction, I'm at a loss what I could suggest right now.
On another note, I can REUSE x to get rid of my ugly ternary and its ambiguity:
c += x*(Math.abs(mod) << i);

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