I am just learning C# and looking deeper into data types.
Why isn't a bool
data type 1 bit in size?
It seems it can only hold one of two values (true or false), so wouldn't that only take up 1 bit of space to represent that value?
Is it because the smallest 'addressable' size of a value is a byte (8 bits) as referred to in this post?
My overall aim was to logically envisage the different size of each data type in C# so I was trying to create a list of all data types and their allocated bit size and this threw me.
A bool takes in real 1 bit, as you need only 2 different values. However, when you do a sizeof(bool), it returns 1, meaning 1 byte. For practical reasons, the 7 bits remaining are stuffed. you can't store a variable of size less than 1 byte.
A bool can be 1 byte or more, depending on the implementation. See fundamental types. it's 1byte (8 bits), Use bitfields or manually write code to access bits in memory buffer.
Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False.
Is it because the smallest 'addressable' size of a value is a byte
Yep, exactly the same thing. In order for the CLR to be efficient, it maps its data types to the native machine data types in much the same way as the compiler does in C++ (pretty much).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With