What is the binary representation of a boolean value in c#

bool is a built-in basic type in C#. Any underlying representation would be an implementation detail.

The C# 4.0 Language Specification states in section 4.1.8:

The bool type represents boolean logical quantities. The possible values of type bool are true and false.

No standard conversions exist between bool and other types. In particular, the bool type is distinct and separate from the integral types, and a bool value cannot be used in place of an integral value, and vice versa.

In the C and C++ languages, a zero integral or floating-point value, or a null pointer can be converted to the boolean value false, and a non-zero integral or floating-point value, or a non-null pointer can be converted to the boolean value true. In C#, such conversions are accomplished by explicitly comparing an integral or floating-point value to zero, or by explicitly comparing an object reference to null.

If we take this one level deeper and see how the corresponding type is specied in the Common Intermediate language (CIL) we will see that a CLI Boolean type occupies 1 byte in memory. The Common Language Infrastructure (CLI) specification says in Partition III, section 1.1.2:

A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeroes denotes a value of false. A bit
pattern with any one or more bits set (analogous to a non-zero integer) denotes a value of true.

However, this is specified on another level and from within C# you should not have to care; even if a future version of the CLI specification might change the representation of the boolean type, or if the C# compiler decided to map a bool in C# to something different, your C# code would still have the same semantics.

Leave a Comment