Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: naked switches Date: Sun, 11 Jul 2021 00:39:28 -0700 Organization: A noiseless patient Spider Lines: 28 Message-ID: <865yxh8fkf.fsf@linuxsc.com> References: <06a0049a-2d7d-40f0-899a-fb35c9a15d5fn@googlegroups.com> <8735sp8cbm.fsf@nosuchdomain.example.com> <255c09e7-2365-4983-ad4d-3bfc83cf04e7n@googlegroups.com> <31342574-cb69-4ad6-8576-387dcf9caf70n@googlegroups.com> <7e094b82-01be-4d7f-9793-4eeda725ca0en@googlegroups.com> <20210708103653.702@kylheku.com> <9a999021-6733-4d00-91fb-9797570a1328n@googlegroups.com> <87czrr3ics.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="52e1adecb53146628fb5ee5c083fc413"; logging-data="8554"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18+Izq2OSUPwB2ZIEvoVGLpZoSE5BDpjh4=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:x3NLWlX08eGMtroID6YOOyZ4wrI= sha1:BquvgjAt9FaPTOIB/Mp6PoK/0EY= Xref: csiph.com comp.lang.c:161868 Ben Bacarisse writes: > David Brown writes: > >> Your extension [for extracting contiguous bits from a word] is not >> commonly used, because it only exists in your tool. People who need >> to do a lot of bit slicing and don't like masking and shifting (or >> struct bit-fields) should not have trouble defining: >> >> #define BIT(x, top, bottom) \ >> (((x) >> (bottom)) & ((1llu << ((top) - (bottom) + 1)) - 1)) >> >> Yes, the parenthesis you need for macros are ugly, but you only need to >> get it right once, and now you can read your bit-fields. > > That's undefined when all the bits are wanted. (The left shift of 1llu > could be equal to the width.) Maybe you wrote it for a compiler that > documents an extension. > > I usually right shift -1llu by the width minus the number of bits > wanted, but you can also just do two left shifts. Another way, assuming the mask width desired is greater than zero, is this ((1LLU << width-1) -1) *2 +1 which works great if 'width' is a compile-time constant.