Hacker News new | ask | show | jobs
by kutkloon7 3219 days ago
I remember a recent example. What I wrote was:

    int x = somefunction();
    int x_dividedby16 = x >> 4;
My coworker corrected the second line to something like:

    int x_dividedby16 = (int)Math.ceil(x / 16.0);
3 comments

I'd only ever use a bitshift if the intention of the code was to move the bits left or right (e.g. moving red, green or blue pixel component bits into the right position) or if it was absolutely required for speed as it's less readable if your intention is to divide a number. C compilers will easily optimise simple integer divisions like this for example.
Did your coworker correct it with "this is more readable" or "this is the correct way to do it"? The first is arguable (though I don't personally agree with the argument), the second just betrays a real lack of knowledge.
Don't the two bits of code have completely different behaviour? And the code with the bitshift is undefined on negative integers (in C). So the bottom code could indeed be the "correct way to do it".
Fair, with negative ints they're different. They have the same behavior on positive ints, though.
Why not `x / 16`?
Integer division will give a rounded result instead of floor
I think they're going for the ceiling here, not the floor. Truncation of positive values should be the same as a floor function.
Yes, I wrote the example. Then realized it was different and corrected only half of it.
Not in C..?

   (x + 15) / 16
Yes, which is more readable and would be compiled to the same thing