Mar 25, 2025

[Bits manipulation]

align:

 
template<size_t S, class T>
inline T align(T value) {
  return (value + (S - 1)) & (~(S - 1));
}

has_single_bit:

 return x && !(x & (x - 1));

midpoint:

  return (a & b) + (a ^ b) / 2;

負i保

  value & (~value + 1);
減一去

  value & (value - 1);
Set union A | B 
Set intersection A & B 
Set subtraction A & ~B 
Set negation ALL_BITS ^ A or ~A 
Set bit A |= 1 << bit 
Clear bit A &= ~(1 << bit) 
Test bit (A & 1 << bit) != 0 
Extract last bit A & -A or A & ~(A - 1) or x ^ (x & (x - 1)) 
Remove last bit A & (A - 1) 
Get all 1-bits ~0

// count bits set
auto num_bits_set(unsigned long num) {
  unsigned result = 0;
  while (num) {
    result++;
    num &= num - 1;
  }
  return result;
}

Use `xor` to set to 0;

popcnt


std::span with argv
#include <cstdio>
#include <span>
int main(int argc, const char *argv[]) {
  puts ( "Greetings to:") ;
  for (auto arg : std::span<const char *>(argv, argv + argc)) {
    puts(arg) ;
  }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.