Re: portable way to get highest bit set?
jak <[email protected]> Thu, 12 Oct 2023 15:09:13 +0200
| Newsgroups | comp.lang.c,alt.comp.lang.c |
|---|---|
| Organization | A noiseless patient Spider |
| Message-ID | <[email protected]> |
Ben Bacarisse ha scritto: > jak <[email protected]> writes: > >> Ben Bacarisse ha scritto: >>> jak <[email protected]> writes: >>> >>>> candycanearter07 ha scritto: >>>>> Hi, >>>>> What is the best/most portable way to get the highest bit set? >>>>> ie. 011010001 >>>>> to 010000000 >>>> >>>> Hi, >>>> I don't think it's the best but the most portable could be the >>>> mathematical approach: >>>> >>>> #include <stdio.h> >>>> #include <math.h> >>>> >>>> int main() >>>> { >>>> unsigned long val = 3000, ret; >>> Test case: val = 0xFFFFFFFFFFFFFFFF >> >> This is due to the approximation of the floating point: > > I know the reason. I was just pointing out that you need to at least > test the boundary cases! > You were really kind to answer. I was also reading about 'feivatround' and like you I found the 'short blanket'. I think there are less complicated and, however, easily portable methods. Such as this: #include <stdio.h> #include <math.h> unsigned long h_bit(unsigned long val) { int i; for(i = -1; val; val /= 2, i++); return (unsigned long)pow(2., (double)i); } int main() { unsigned long val = ~0UL, ret; ret = h_bit(val); printf("\nv: %lX r: %lX", val, ret); return 0; } Finally, the simplest things seem to be the best. Thanks again.