Hacker News new | past | comments | ask | show | jobs | submit login

You don't need syntactical sugar. Just write a function.

    static bool all_bits_set(i32 value, i32 mask) { return (value & mask) == mask; }
Here I'm assuming 32-bit values. In C, with relatively little support for generics, you can consider making multiple versions, possibly using _Generic (note, I haven't evaluated the sanity of using _Generic).

Alternatively you can use a #define. However, you need to use "mask" twice, so that gets tricky - either it requires care to keep the corresponding expression at the call site side-effect free. Or the macro needs to be written using compiler extensions like statement expressions and typeof() variable declarations à la Linux kernel.




Yeah the usual way in C would be to use statement expression (which is a GCC extension but is supported by at least clang and msvc)

    #define all_bits_set(value, mask) ({__typeof__(value) v = (value), m = (mask); (v & m) == m; })
I personally would go for the extension aboveor a single 64 bit function, but here's the _Generic version:

    static bool all_bits_set32(i32 value, i32 mask) { return (value & mask) == mask; }
    static bool all_bits_set64(i64 value, i64 mask) { return (value & mask) == mask; }
    #define all_bits_set(value, mask) _Generic((value), int32_t: all_bits_set32, int64_t: all_bits_set64)(value, mask)


The nice thing about this is that it's simple and works pretty much in any language so there's very little cognitive strain if you work with multiple languages at the same time.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: