use __builtin_clz to compute most significant bit set

Started by Joseph Yuover 3 years ago2 messageshackers
Beta feature

Hackorum builds and tests every patch posted to the lists, not only commitfest submissions. This is Hackorum's own CI rather than the PostgreSQL project's, and it is still under testing - please report anything that looks wrong.

won't retrysuccessCI history

You can run a PostgreSQL built from this patch straight from Docker, with no checkout and no build:

docker run --rm -p 5432:5432 ghcr.io/hackorum-dev/postgres-patch:t47523
psql -h localhost -U postgres

Built from patchset v1 (message #1), July 27, 2026 at 01:38 PM.

Every patchset is also pushed to a branch of our PostgreSQL fork, so you can check out the same tree CI built. Without a PostgreSQL checkout:

git clone --branch t47523_1 https://github.com/hackorum-dev/postgres.git

In a checkout you already have, add the fork once:

git remote add hackorum https://github.com/hackorum-dev/postgres.git

then, for this patchset and every later one:

git fetch hackorum t47523_1 && git checkout t47523_1

Patchset v1 (message #1) is on t47523_1

Jump to latest
#1Joseph Yu
kiddo831007@gmail.com

hi community

This is the first time for me to submit a patch to Postgres community.

instead of using for loop to find the most significant bit set. we could
use __builtin_clz function to first find the number of leading zeros for
the mask and then we can find the index by 32 - __builtin_clz(mask).

diff --git a/src/port/fls.c b/src/port/fls.c
index 19b4221826..4f4c412732 100644
--- a/src/port/fls.c
+++ b/src/port/fls.c
@@ -54,11 +54,7 @@
 int
 fls(int mask)
 {
- int bit;
-
  if (mask == 0)
  return (0);
- for (bit = 1; mask != 1; bit++)
- mask = (unsigned int) mask >> 1;
- return (bit);
+ return (sizeof(int) << 3) - __builtin_clz(mask);
 }

Best Regards,

Joseph

Attachments:

t47523_1
fls.patchtext/x-patch; charset=US-ASCII; name=fls.patchDownload+1-5
#2Magnus Hagander
magnus@hagander.net
In reply to: Joseph Yu (#1)
Re: use __builtin_clz to compute most significant bit set

On Sat, Feb 25, 2023 at 9:32 PM Joseph Yu <kiddo831007@gmail.com> wrote:

hi community

This is the first time for me to submit a patch to Postgres community.

instead of using for loop to find the most significant bit set. we could
use __builtin_clz function to first find the number of leading zeros for
the mask and then we can find the index by 32 - __builtin_clz(mask).

Hi!

This file has already been removed, as of 4f1f5a7f85. Which already uses
__builtin_clz if it' available.

Were you perhaps looking at an old version instead of the master branch?

--
Magnus Hagander
Me: https://www.hagander.net/ <http://www.hagander.net/&gt;
Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/&gt;