Quick actions

cmd+k|ctrl+k

Navigation

Languages

Get frist 0 / first 1 of bit-representation of integer

Snippet info

Language

C

Visibility

public

Author

dokel

Created

2018-12-23T18:33:45Z

Updated

2018-12-23T18:33:45Z

#include <stdio.h>
#include <math.h>
#define CHAR_BIT 8
#define INT_BIT CHAR_BIT*sizeof(unsigned int)

void sb(unsigned int* a, unsigned char pos){
    *a |= 1 << (INT_BIT-pos-1);
}

int getPosition(unsigned int a){
    float logg = log2(a);
    return (INT_BIT - (int)floor(logg)) - 1;
}

int main(void) {
    unsigned int a = 0;
    sb(&a, 1);
    sb(&a, 2);
    sb(&a, 3);
    sb(&a, 5);
    sb(&a, 6);
    
    printf("Poisiton of first 1 is: %d\n", getPosition(a));
    printf("Poisiton of first 0 is: %d\n", getPosition(~a));
    return 0;
}
INFO