0

From the previous question about Set n least significant bits to 1, and the great answer from that, I've written a function to find if a positive integer is a power-of-two:

# Is 16 a multiple of 8 (2^3)? Yes
mov $16, %edi
mov $3, %esi
call pow_2_short

pow_2_short:
    mov $1, %eax
    mov %sil, %cl # move low byte of %esi (the power of 2) into %cl for the shift
    shl %cl, %eax
    dec %rax
    test %eax, %edi
    jz _set_true; jnz _set_false
  _set_false:
    xor %eax, %eax
    ret
  _set_true:
    mov $1, %eax
    ret

My main question about this is the conditional part which seems a bit odd to me. Is the above pattern a common way to basically do:

if x:
    // do this
else:
    // something else

If not, what's a more idiomatic way to do that?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 2
    If you want to return a boolean, `test` / [`setz %al`](https://www.felixcloutier.com/x86/setcc). Look at compiler output, compilers know how to use the ISA efficiently, and know a bunch of bit-manipulation tricks. But yes, `jz else` and fall through into the `if` body is the idiomatic way. You included a totally useless `jnz _set_false` that is always taken if reached, and jumps to the next instruction where execution would fall through to anyway. – Peter Cordes Sep 25 '20 at 04:56
  • Also note that with BMI2, you could implement this function as `bzhi %esi, %edi, %edi` (clear bits above a given position) / `setz %al` / `ret`. – Peter Cordes Sep 25 '20 at 04:59
  • Also, you're checking if a number is a *multiple* of 8, not a *power*. The *powers* of 8 are 8, 64, 512, 4096, and so on. The trick you're using is checking for a multiple of a power-of-2. – Peter Cordes Sep 25 '20 at 05:00
  • @PeterCordes got it -- thanks for the tip with `setz` -- now I've learned a new instruction I can use -- and yes regarding your last comment about divisible vs. power, I mis-stated that. – samuelbrody1249 Sep 25 '20 at 05:02
  • You would have already learned it on your own if you'd take some time to look at C compiler output. (And probably have answered yourself some other questions you've asked, possibly including this one). [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) – Peter Cordes Sep 25 '20 at 05:26

0 Answers0