Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Bit field usage Date: Sun, 27 Oct 2019 04:54:50 -0700 Organization: A noiseless patient Spider Lines: 43 Message-ID: <86o8y2flo5.fsf@linuxsc.com> References: <1bo8y6azlw.fsf@pfeifferfamily.net> <86woctfy1g.fsf@linuxsc.com> <1bwocsalcq.fsf@pfeifferfamily.net> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="317be1caa85c1e9ffa508e672fec29a2"; logging-data="24581"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Xqof8f7qOZkIyKWJK5UylW3fVtt5brUk=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:y0R+DRf51dq4Bb5HoN8gJvyE1Zg= sha1:gcRkiFBxi9ZWZOqXOUhAt2/qcbs= Xref: csiph.com comp.lang.c:147282 Joe Pfeiffer writes: > Tim Rentsch writes: > >> Joe Pfeiffer writes: >> >>> jacobnavia writes: >>> >>>> 1) To access a bitfield, the compiler generates a sequence of shifts >>>> that increases execution time. >>>> >>>> 2) The instructions sequence of the shifts increases code size. >>>> >>>> Obviously, if you have more than 64 flags (in a 64 bit machine) or >>>> more than 32 flags in a 32 bit machine, bitfields can save a lot of >>>> data space: you can fit up to 128 bitfields in 16 bytes, instead of >>>> 128 bytes if you use a full char for each bit field. >>>> >>>> It is important to check two things: >>>> 1) If a bit field is heavily used, consider transforming it into an >>>> unsigned char. >>>> 2) If you have a few bit fields with bitsize less than the word size >>>> of your machine, consider if the alignment requirements are nullifying >>>> any space gains obtained by using bit fields. >>> >>> I got burned badly enough by bitfields doing unexpected things decades >>> ago that I abandoned them and do my own shifts and masks. >> >> Out of curiosity, what kind of problems did you run into? > > It was a long time ago... if I remember correctly (always a big if!) I > was using them to construct things like instruction and floating point > formats, and things got scrambled in the switch from Motorola 680x0 to > Sparc. Do you remember anything else? This tells me when you ran into some problems but not what the problems were. Might the problems have been not with bitfields per se but just with platform differences? Making a guess, maybe you simply found it easier to get things right (for the two platforms) using shifting and masking than using two sets of bitfields? I think bitfields work pretty well for a single platform, but are sometimes hard to get right if dealing with multiple platforms.