Skip to content

Instantly share code, notes, and snippets.

@Blokyk
Last active January 22, 2024 01:38
Show Gist options
  • Save Blokyk/db740aef543eeb48cebead252834b585 to your computer and use it in GitHub Desktop.
Save Blokyk/db740aef543eeb48cebead252834b585 to your computer and use it in GitHub Desktop.
#include <stdint.h>
// --- popcnt as a C integer constant expression ---
// this is the kinda bullshit required when you can't use C++ >:|
#define __const_popcnt2(val) ((val) == 0 ? 0 : ((val) == 2 ? 2 : 1))
#define __const_popcnt4(val) (__const_popcnt2((val) & 0b11) + __const_popcnt2((uint8_t)((val) & 0b1100) >> 2))
#define const_popcnt8(val) (__const_popcnt4((val) & 0b1111) + __const_popcnt4((uint8_t)(val) >> 4))
#define const_popcnt16(val) (const_popcnt8((val) & 0b11111111) + const_popcnt8((uint16_t)(val) >> 8))
#define const_popcnt32(val) (const_popcnt16((val) & 0b1111111111111111) + const_popcnt16((uint32_t)(val) >> 16))
#define const_popcnt64(val) (const_popcnt32((val) & 0b11111111111111111111111111111111) + const_popcnt32((uint64_t)(val) >> 16))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment