C++ Logo

std-proposals

Advanced search

Re: [std-proposals] More C++ bit manipulation utilities

From: Jan Schultke <janschultke_at_[hidden]>
Date: Fri, 27 Jun 2025 09:30:24 +0200
> Or if you want to avoid branches and are okay with a few extra cycles:
> uint32_t filled = ((test_var >> 31) & 0x01) * 0xFFFFFFFF;

If you operate on a signed integer, you don't need anything but >> 31.

The hard part is figuring out exactly by how many bits to shift using
std::numeric_limits, and possibly performing a sign conversion back
and forth if your input is unsigned, so that you do an arithmetic
right shift instead of a logical right-shift.

This idea of using hex masks is also introducing a lot of magic
numbers into your code, and doesn't work very well when you write
generic code that is meant to cover at least 32-bit and 64-bit
integers in a single template.

Come to think of it, I'm starting to see a theme here. You sometimes
want to use arithmetic right shifts on unsigned operands, you
sometimes want to sign-fill, and sometimes you want to get the bits
that have been "shifted out" in for multi-precision bit operations
etc. This could make a good theme for the proposal overall, and
there's decent motivation for such function templates.

Received on 2025-06-27 07:30:37