-2

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;

1 Answers1

2
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; 
}
Jim Balter
  • 16,163
  • 3
  • 43
  • 66
  • I feel `return x & (1 << bit)` is enough. – Jeyaram Feb 06 '14 at 06:14
  • 1
    @Jeyaram You feel wrong ... the requirement is to return 1 if the bit is set, not `1 << bit`. If I were interviewing you, I would blackball you for that. OTOH, `(x >> bit) & 1` is ok, but more obscure. – Jim Balter Feb 06 '14 at 06:15