Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C bit twiddling so that Zero => 1 while Non-Zero => -1? (ideally x86 intrinsic)

I’m looking for a way to achieve what I wrote in the title.
I’m doing it now with an "if" and I want to get rid of branching.
I’ve had a look at a couple of pages such as this one, can’t find the exact thing I’m looking for.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Converting x to a boolean does not generate any branches on current x86 processors. You can use simple arithmetics to generate your result:

int test_zero(int x) {
    return 1 - 2 * !!x;
}

gcc 11.2 generates this:

test_zero:
    cmp     edi, 1
    sbb     eax, eax
    and     eax, 2
    sub     eax, 1
    ret

clang 13.0.0 generates this:

test_zero:                              # @test_zero
    xor     eax, eax
    test    edi, edi
    sete    al
    add     eax, eax
    add     eax, -1
    ret

You check the code generation on Godbolt’s compiler explorer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading