1

Assume I want to reserve 8 bytes on the stack and I also want to make sure current stack pointer is 8 byte aligned. I have seen some codes that assure current sp is 8 bye aligned using this logic:

sp = sp & -8;

They AND it with the amount they are going to reserve on the stack (which of course is negative).

How does this logic work?

markalex
  • 8,623
  • 2
  • 7
  • 32
Dan
  • 577
  • 1
  • 3
  • 9

1 Answers1

0

It works because negative numbers are represented in two's complement, so -8 is equivalent to ~7, of which the 3 least significant bits are 0s and the rest are 1s. ANDing this with a value clears the 3 least significant bits, which obviously results in it being 8-byte aligned. By the way, this trick only works to align things to powers of 2. If you had some strange reason to align things to a 12-byte boundary, for example, sp = sp & -12 would not work as intended.