Path: csiph.com!news.mixmin.net!eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: portable way to get highest bit set? Date: Sun, 15 Oct 2023 01:44:39 -0700 Organization: A noiseless patient Spider Lines: 30 Message-ID: <86lec48ebs.fsf@linuxsc.com> References: <20231011143809.748@kylheku.com> <20231014222046.551@kylheku.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: dont-email.me; posting-host="eb478ed0db5b06d993c3ccd040701c7e"; logging-data="440333"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19cqKIvvx+TZH5n7ByM8q38613ogxEBEng=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:9CL6hokuQPSaJOrA9D5fZ7FgA0w= sha1:TWM5SJpZUMquuT/D5Lfs9fWX1kU= Xref: csiph.com comp.lang.c:272722 Kaz Kylheku <864-117-4973@kylheku.com> writes: > On 2023-10-11, Kaz Kylheku <864-117-4973@kylheku.com> wrote: > >> E.g. 32 bit code: >> >> uint32_t fill_mask_down(uint32_t x) >> { >> x |= x >> 1; // e.g. 1000...0000 -> 1100...0000 >> x |= x >> 2; // e.g. 1100...0000 -> 1111...0000 >> x |= x >> 4; // e.g. 11110000... -> 11111111... >> x |= x >> 8; >> x |= x >> 16; >> >> return x; >> } >> >> Thus: >> >> uint32_t isolate_highest_bit(uint32_t x) >> { >> uint32_t m = fill_mask_down(x); >> return m ^ (m >> 1); >> } > > I guess this went over people's heads? Not at all. It's a well-known technique. But it doesn't address the central ask for an approach that works no matter how wide the value type is.