Why isn't the size of a bool data type only 1 bit in C#?

巧了我就是萌 提交于 2019-12-04 15:33:51

问题


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.


回答1:


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).




回答2:


If you want to store lots of flags in a space-efficient way, consider using Int32 or Int64 as a bitmask, this way you can store 32 or 64 boolean flags in a 32 / 64 bit data type. You have to do bitmask tests to check or set values, so there's a small addition cost to access or update, over a Boolean variable.

The size of a Boolean field in memory is 1 byte, and of a Boolean variable is 4 bytes.

BitArray is also handy for dealing with lots of bit flags: http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx




回答3:


I noticed this as well... I created two arrays: float[4000] and float?[4000]. The second array takes twice the memory space because float? is implemented as a float and a bool, and the bool ends up taking 32 bits just the same as the float does.

So in the end, if memory usage is a concern, using a NaN float value to represent "null" in a float[] is better than using a float?[].

Makes me feel like an idiot for all the years I tried to use smaller data types believing it was actually doing some good! :-)



来源:https://stackoverflow.com/questions/17745234/why-isnt-the-size-of-a-bool-data-type-only-1-bit-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!