Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

Liam McGillivray yoshi.pit.link.mario at gmail.com
Sat Mar 16 21:16:51 UTC 2024


On Friday, 15 March 2024 at 00:21:42 UTC, H. S. Teoh wrote:
> On Thu, Mar 14, 2024 at 11:39:33PM +0000, Liam McGillivray via 
> Digitalmars-d-learn wrote: [...]
>> I tried to rework the functions to use bitwise operations, but 
>> it was difficult to figure out the correct logic. I decided 
>> that it's not worth the hassle, so I just changed the value 
>> storage from `bool[3]` to `ubyte`.
> [...]
>
> Just wanted to note that while in theory bool[3] could be 
> optimized by the compiler for compact storage, what you're most 
> likely to get is 3 bytes, one for each bool, or perhaps even 3 
> ints (24 bytes). When dealing with units of data smaller than a 
> byte, you generally need to do it manually, because memory is 
> not addressable by individual bits, making it difficult to 
> implement things like slicing an array of bool. So the compiler 
> is most likely to simplify things by making it an array of 
> bytes rather than emit complex bit manipulation code to make up 
> for the lack of bit-addressability in the underlying hardware.
>
> Using bit operators like others have pointed out in this thread 
> is probably the best way to implement what you want.
>
> T

I'm curious as to what "manual implementation" would mean, since 
clearly making my own struct with `bool[3]` doesn't count. Does D 
have features for precise memory manipulation?

Anyway, I'm surprised that D has a special operator `&=` for 
doing bit manipulation on integers, especially given that the 
steps to convert an int into a bool array is more complicated. I 
would imagine the former would be a rather niche thing.


More information about the Digitalmars-d-learn mailing list