问题描述
我知道布尔值是 1 个字节(8 位长)但我想知道它的二进制表示是什么.例如十进制 => 二进制4 => 100 (0000 0100)8 => 1000 (0000 1000)布尔值 => ???
I know that a boolean value is 1 byte (8 bits long) But I would like to know is what is its binary representation. e.g. decimal => binary 4 => 100 (0000 0100) 8 => 1000 (0000 1000) bool value => ???
推荐答案
bool
是 C# 中内置的基本类型.任何底层表示都是实现细节.
bool
is a built-in basic type in C#. Any underlying representation would be an implementation detail.
C# 4.0 语言规范在第 4.1.8 节中声明:
The C# 4.0 Language Specification states in section 4.1.8:
bool
类型表示布尔逻辑量.bool
类型的可能值为 true
和 false
.
The
bool
type represents boolean logical quantities. The possible values of typebool
aretrue
andfalse
.
bool
与其他类型之间不存在标准转换.特别是,bool
类型与整数类型截然不同,并且不能使用 bool
值代替整数值,反之亦然.
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.
在 C 和 C++ 语言中,零整数或浮点值,或空指针可以转换为布尔值 false
,以及非零整数或浮点值,或者非空指针可以转换为布尔值true
.在 C# 中,此类转换是通过显式将整数或浮点值与零进行比较,或者通过将对象引用显式与 null 进行比较来完成的.
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.
如果我们更深入一层,看看在通用中间语言 (CIL) 中是如何指定相应类型的,我们将看到 CLI 布尔类型在内存中占用 1 个字节.Common Language Infrastructure (CLI) 规范在第 III 部分第 1.1.2 节中说:
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:
CLI 布尔类型在内存中占用 1 个字节.全为零的位模式表示值为假.一点点设置了任何一个或多个位的模式(类似于非零整数)表示值为真.
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.
但是,这是在另一个级别上指定的,并且在 C# 中您不必关心;即使 CLI 规范的未来版本可能会更改布尔类型的表示,或者如果 C# 编译器决定将 C# 中的 bool
映射到不同的东西,您的 C# 代码仍然具有相同的语义.
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.
这篇关于c#中布尔值的二进制表示是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!