Вопрос

I have to return 1 if bit i in x is set, 0 otherwise in is_set function. I got stuck here. Have no idea what to do next...Any ideas?? Any help will appreciated....

#include <string.h>
#include <stdio.h>

const char *to_binary(unsigned int x) {
    static char bits[17];
    bits[0] = '\0';
    unsigned int z;
    for (z = 1 << 15; z > 0; z >>= 1) {
        strcat(bits, (x & z) ? "1" : "0");
    }
    return bits;
Это было полезно?

Решение

short is_set(unsigned short x, int bit) {
    return x & (1 << bit) ? 1 : 0; 
}

Alternatively,

short is_set(unsigned short x, int bit) {
    return (x >> bit) & 1; 
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top