Public Group

Divisible by 8

This topic is 3495 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

If val is unsigned int, can I just check val & 0x7 ?

Share on other sites
For divisible by 2, you check bit 0.
For divisible by 4, you check bits 0, 1.
For divisible by 8, you check bits 0, 1, 2.

So, yes.

Share on other sites
It should also work for negative numbers if my understanding is correct.
0 0 0 0 1 0 0 0 (8)1 1 1 1 0 1 1 11 1 1 1 1 0 0 0 (-8)0 0 0 1 1 0 0 0 (24)1 1 1 0 0 1 1 11 1 1 0 1 0 0 0 (-24)

EDIT: opps apparently I cant add 1 :)

[Edited by - Fire Lancer on May 21, 2009 9:03:55 AM]

Share on other sites
Quote:
 Original post by PruneIf val is unsigned int, can I just check val & 0x7 ?

Yes.
inline bool divisible8(unsigned val){    return (val & 7) == 0;}

Share on other sites
Quote:
 Original post by Fire Lancer0 0 0 1 1 0 0 0 (24)1 1 1 0 0 1 1 11 1 1 0 1 0 0 0 (-24)

Fixed =P (otherwise it was -8)

Though yeah. In fact, if you use % 8 instead and the compiler has optimizations enabled, it will most likely do the replacement. This is also true for multiplication and division by powers of two (when using integers, of course), where they get replaced by shifting to left and right whatever amount is needed to do the equivalent, respectively.

EDIT: misquoting (missing tag >_<')

EDIT 2: typo. Is it obvious that I just woke up >_>'

1. 1
2. 2
Rutin
15
3. 3
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• Forum Statistics

• Total Topics
633725
• Total Posts
3013559
×