4

I'm trying to make a program which prints out the position of the leftmost 1 bit in C, but without loops.

This is what I've gathered so far:

#include<stdio.h>
int main() {
    unsigned int x, y;
    printf("Enter an integer: ");
    scanf("%d", &x);
    // Bit 
    x |= x >> 4;
    x |= x >> 2;
    x |= x >> 1;
    x ^= x >> 1;
    printf("\n%d", x);
    return 0;
}

This prints out the leftmost bit as an integer, but I'm having trouble converting it to the position of its highest set bit.

128 should be 8 (1000 0000) 64 should be 7 (0100 0000)

1 Answers1

0

Inspired from this question, this solution that define a loopless popcnt() should solve your problem:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

static inline uint32_t popcnt(uint32_t x) {
    x -= ((x >> 1) & 0x55555555);
    x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
    x = (((x >> 4) + x) & 0x0f0f0f0f);
    x += (x >> 8);
    x += (x >> 16);
    return x & 0x0000003f;
}

static inline uint32_t firstset(uint32_t x) {
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return popcnt(x);
}

int main() {
    uint32_t x;

    printf("Enter an integer: ");
    scanf("%"SCNu32, &x);

    printf("%"PRIu32"\n", firstset(x));

    return 0;
}
Giovanni Cerretani
  • 1,693
  • 1
  • 16
  • 30