# Thread: Determine if a number lies on a 4-byte boundary

1. ## Determine if a number lies on a 4-byte boundary

I've been racking my mathless brain for the last 45 minutes, looked at two books (if Bit Twiddling Hacks counts as a book) all to no avail.

The answer is no doubt really obvious. I'm tired. Very, very tired.

EDIT: Yes, I have googled.

2. I'm not quite sure what you're asking here. If you want to find whether a number can be stored in 4 bytes, I'd check whether it's less than 2^32.

QuantumPete

3. I want to know if it's dead on a 4-byte boundary, like is it equal to 32, 64, 96 etc. I guess I could use a lookup table with a search, but I was hoping there's a way of calculating it.

4. Hmm, you could mod it with for 4...

5. Or I could shoot myself in the FACE for being so stupid. Thank you.

6. Originally Posted by ahluka
Or I could shoot myself in the FACE for being so stupid. Thank you.
No problem ;-)

7. >I want to know if it's dead on a 4-byte boundary, like is it equal to 32, 64, 96 etc.
Code:
`    if ((num & 0x1f) == 0)`

8. The normal way to check the alignment is to and with alignment-1 and check that it's zero, e.g.
Code:
```   if ((address & 3) == 0) ... // it's aligned
else ... // unaligned.```
If you want to make it generic, you could do:
Code:
`   if ((address & sizeof(type)-1) == 0) ...`
This works for all types that have sizes that are 2^n, e.g 2, 4, 8, 16, 32, 64, etc.

Note that the parenthesis around (address & x) are necessary, otherwise the compiler will evaluate 3 == 0 [or whatever] first, then perform the and. If it's false, like in this case, it will be false all over, since X & 0 is always zero, so false. Don't ask me how I remember this, just trust me that if you've made the same mistake enough times, you don't forget quite so easily.

--
Mats

Popular pages Recent additions