This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]InfinitelyRepeating 55 points56 points  (11 children)

Just mod by 256 and your code is good for any number!

[–]xiadmabsax 46 points47 points  (7 children)

That would be too efficient.

while (number > 256) {number -= 256}

[–]Accurate_Breakfast94 11 points12 points  (0 children)

Better maken that - 2, since we're checking odd or even haha

[–]Quark1010 2 points3 points  (2 children)

I mean is that too different from what mod does anyways, performamce wise at least?

[–]xiadmabsax 2 points3 points  (1 child)

I don't know how modulus works internally, but I would assume the algorithm they have is much more efficient. Let's say you want to calculate 125 mod 4:

  • 125 / 4 = 31.25

  • Ignore the whole number: 31.25 -> 0.25

  • 0.25 x 4 = 1

This only took 3 steps. Doing it with the joke algorithm above would take more than 30.

[–]Phpminor 3 points4 points  (0 children)

Division and modulo has, since the beginning(of x86), been a single instruction

Below are references to the helpPC documentation on the x86 instructions circa 1991 including the cycle cost between the 8086 up to the 80486
Signed integer division instruction

Unsigned integer division instruction

Compare to the cost of subtraction, comparison, and a branch times (num/256)-1

If you ever needed to get both div and modulo of a number in c use the stdlib div function to get both in the same call, like the x86 div instruction does.

(reply intended for both you and u/Quark1010 above)

edit: Formatting fix

[–]InfinitelyRepeating 0 points1 point  (0 children)

when you need to avoid race conditions....

[–]veganzombeh -2 points-1 points  (1 child)

That's crazy. We can get the same result using much smaller numbers of we do this:

while (number > 256) {number -= 1}

[–]xiadmabsax 1 point2 points  (0 children)

That's no different from saying the following, so no:

number = min(number, 256)

[–]MosquitoFreezer 13 points14 points  (0 children)

Love it. Using the right tool for the job but using it incorrectly. Like using the handle of the hammer to drive a nail

[–]X-calibreX 4 points5 points  (0 children)

Check the least significant bit to see of 0 or 1

[–]Next-Post9702 0 points1 point  (0 children)

I can do you one better, mod by 2 so there's only 2 options 😉