Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #228549
| Path | csiph.com!news.mixmin.net!eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail |
|---|---|
| From | Tim Rentsch <tr.17687@z991.linuxsc.com> |
| Newsgroups | comp.lang.c |
| Subject | Re: portable way to get highest bit set? |
| Date | Wed, 11 Oct 2023 10:34:53 -0700 |
| Organization | A noiseless patient Spider |
| Lines | 57 |
| Message-ID | <86h6mxawqq.fsf@linuxsc.com> (permalink) |
| References | <ug5gvh$1jkar$3@dont-email.me> <20231011102714.44a870af4dfe68f756974953@g{oogle}mail.com> <ug6huc$1rvp1$1@dont-email.me> |
| MIME-Version | 1.0 |
| Content-Type | text/plain; charset=us-ascii |
| Injection-Info | dont-email.me; posting-host="c9974d524a342450c72757464b9d47a6"; logging-data="2064482"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/NUV9052bkxu46JYy3RF8X0n7hSGbXJmM=" |
| User-Agent | Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) |
| Cancel-Lock | sha1:bTndiKAYgdgUEvQ6xp1tG3DoEXA= sha1:gJZ9NozqCS3XLXn6A8GkNkx6Quw= |
| Xref | csiph.com comp.lang.c:228549 |
Show key headers only | View raw
candycanearter07 <no@thanks.net> writes:
> On 10/11/23 02:27, Anton Shepelev wrote:
>
>> candycanearter07:
>>
>>> What is the best/most portable way to get the highest bit
>>> set?
>>>
>>> ie. 011010001
>>> to 010000000
>>
>> What is your best attempt, even if unsuccessful?
>
> int out;
> for(out = 0x100000000; out; out >> 1)
> if(out & input) break;
>
> I'm trying to find something size independent, though.
> Or at least able to be swapped out with a #define
I've coded up a dozen[*] different solutions. Here is my current
favorite[**]:
typedef union {
long double d;
struct { unsigned long long s; unsigned e:15;} b;
} X;
unsigned long long
high_bit_set( unsigned long long u ){
return 1ULL << (X){ .d = u }.b.e - 16383 & u;
}
This answer has these nice properties:
* Single line function body
* No looping or testing
* Large domain of inputs supported
* Widely portable
* Very few cases with undefined behavior
* Forms an excellent basis for several interview questions
* Sure to launch a torrent of followups on its pros and cons
(I'm resisting the temptation to make an off-topic remark
regarding the number of properties.)
P.S. This response is meant to be more entertaining than
useful. I do hope it helps broaden your thinking in
searching for an answer.
[*] that might be a baker's dozen, due to off-by-one error
[**] for some values of "favorite"
Back to comp.lang.c | Previous | Next | Find similar
Re: portable way to get highest bit set? Tim Rentsch <tr.17687@z991.linuxsc.com> - 2023-10-11 10:34 -0700
csiph-web