Sujet : Re: what you can do with bitfields
De : profesor.fir (at) *nospam* gmail.com (fir)
Groupes : comp.lang.cDate : 30. Nov 2024, 23:11:09
Autres entêtes
Organisation : i2pn2 (i2pn.org)
Message-ID : <94eeb2627d1afdb164e0ba8c74ddd8a65affbdf3@i2pn2.org>
References : 1 2 3 4
User-Agent : Mozilla/5.0 (Windows NT 10.0; WOW64; rv:91.0) Gecko/20100101 Firefox/91.0 SeaMonkey/2.53.19
BGB pisze:
On 11/30/2024 9:50 AM, fir wrote:
Lawrence D'Oliveiro pisze:
On Thu, 28 Nov 2024 14:39:43 +0100, fir wrote:
>
i use them but i never fully chcked what i can do with them ...
>
One problem with C is that bitfields can only have static offsets and
sizes. If these were dynamic, you could express much more powerful
manipulations more conveniently than with shifting and masking.
>
what do you mean?
i must check hovever how this static work at all.. i used them
and not so rarely but only simple cases usually for solo bit flags
Most common way to do bit flags:
#define WHATEVER_FLAG1 0x0001
#define WHATEVER_FLAG2 0x0002
...
And:
if(flags&WHATEVER_FLAG1)
{ ... }
Though, for larger bit-flags, on some targets it may be more efficient to do:
if((flags>>WHATEVER_FLAG43_SHR)&1)
{ ... }
For example, RISC-V, where shift-right and mask will use fewer instructions than constant-load and mask.
...
and you thing doin it with bitfields would be worse?
i dont tested such things but i use
union Color
{
unsigned u;
struct { unsigned char b,g,r,a;};
};
in my per-pixel graphics codes to spare unpacking/packing unsigned color into r g b a with shifts and ands or ors
anbd in this case its not only much simpler/shortes yet use this
union is more effective (i tested it bac then some hours and
not met a case when this union woudl be slower than shifts by hand)
(speakin on gcc /tdm for windows)