Handmade Hero»Forums»Code
55 posts
Aligning to 16 bit boundary
Last episode a question about the (value + 1) & -1 confused me and I turned to my debugger for comfort, but without success.

Why does ((value + 15) & -15) align the value to a 16 bit address? I thought Casey used this macro in HH and mentioned it last night, or am I wrong?

But -15 in hexadecimal is 0xfffffffffffffff1, and I'd think it should be 0xFF...0 to work properly.

The results I get for the following values are not aligned to 16:
((0 + 15) & -15) = 1
((16 + 15) & -15) = 17
((14 + 15) & -15) = 17

Obviously I'm doing something wrong or don't remember the macro. What's wrong in my reasoning?
Marc Costa
65 posts
Aligning to 16 bit boundary
The macro for alignment is slightly different: (ptr + (alignment - 1)) & ~(alignment - 1).

For alignment = 16:
~(16 - 1) = ~(15) = ~(0x0000000f) = 0xfffffff0

So, your examples:
((0 + 15) & ~15) = 0
((16 + 15) & ~15) = 16
((14 + 15) & ~15) = 16
55 posts
Aligning to 16 bit boundary
Oh thank you! ~15 = -16. :)