Bitfield structs and suggestion

Richard Bradley darthalias at yahoo.com
Fri Nov 23 08:53:18 PST 2007


Yes, You are right Janice. We want to access the bitfields in a structure as if they were the integers.

Like this:

packet.ip.type_of_service.reliability = 1;

(See http://www.protocols.com/pbook/tcpip2.htm#IP for ip protocol.)

I whole heartedly disagree that your workaround is sufficient. It is a bit like saying C doesn't need native string support because you can just make a character array, or that you can just make a C++ class to handle strings. (We all know how well that works, everyone and their grandmother has a different string class.)

If you look at your example you are replacing the four parameters in the C++ version ( the four bitfield sizes) with twelve parameters in D ( 4 bitfield positions, and 8 masks.) not to mention the shifting and bitwise operations. And the need of the user to keep track of the “bits” members size. Plus, what if you wanted a structure 512 bytes long? Your ushort “bits” would have to be an array, and you would need to be very careful then of how your bitfields mapped into that array. This is adding a lot of accidental complexity to the problem. It's is okay if you are doing this once or twice. But I am literally talking about doing this on thousands of classes per project, on structures that can be quite large.

The D workaround adds quite a bit of error-prone complexity.

I would also like to suggest that this isn't a rarely-used feature. You run into this issue anytime you want to read or write to hardware, (or link to a library that talks to hardware) or access any sort of network protocol stack, or any type of communication protocol. 

As an outsider looking in that works in these domains, this becomes a glaring hole in an otherwise wonderful language. One of my fundamental coding tasks is to talk to hardware, and I don't see that task as at all being rare.

I would agree that the way C++ does bitfields is “inefficient.” I know of no general-purpose language that does this well. The issues of portability (with respect to byte ordering) is valid, but kinda beside the point. If you are hacking hardware, it is by definition tied to the hardware. Just like the windows library is not portable outside windows. Plus, if we fixed that whole byte-order thing it would be a big justification to using the language, as the way C does it is just ugly.

There seems to be a lot of support for a feature along these lines. There has been a good discussion going on for quite some time. The underlying question is do we want D to live in this “low level bare metal “ environment? And if so, what do we (yes, I am including myself) need to do?

~Richard




More information about the Digitalmars-d mailing list