问题描述
我可以在任何一种有意义的方式使用 BOOL *
。我将如何转换 BOOL *
到字节
例如,或者存储 BOOL *
在一个字节
Can I use bool*
in any kind of meaningful way. How would I convert bool*
to a byte
for instance, or store bool*
in a byte
我的目标是管理我的项目我的记忆中,具体细节并不重要,只是一些ID喜欢做的事。现在,我想是能够存储我自己的变量,我碰巧需要存储一个布尔值。我如何使用不安全
和字节*
,保存这个布尔值,并利用我的空间最好?理想的情况下,以4位存储字节。
My goal is to manage my own memory in a project of mine, the specifics aren't important, just something id like to do. Now I would like to be able to store my own variables, and i happen to need to store a boolean value. How can i, using unsafe
and a byte*
, store this boolean value, and utilize my space best? Ideally to store 4 bits in the byte.
推荐答案
在C#中,你一般不会使用 BOOL *
,这是一件好事,你只能使用不安全code(这带来了一大堆其他东西一样钉住对象等等)。 A BOOL *
将是一个指向一个布尔值。指针是4字节长,并且不能被转换为一个字节,而不损失
In C# you wouldn't normally use a bool*
, which is something you can only use in unsafe code (which brings forth a whole lot of other stuff like pinning objects and so forth). A bool*
would be a pointer to a boolean. A pointer is 4 bytes long and cannot be converted to a byte without loss.
为什么要做到这一点,你会遇到这样的在哪里?通常情况下,有不容易用例在C#中使用指针,除非你有一个非常明确的要求(即API调用,但可以解决使用P / Invoke)。
Why would you want to do this and where do you encounter this? Normally, there's not easily a use case for using pointers in C# unless you have a very specific demand (i.e., an API call, but that you can solve using P/Invoke).
编辑:(因为你编辑你的Q)
(because you edited your q.)
以下code段显示如何获得布尔变量的地址,以及如何为该指针转换为 INT
(转换为字节
是不可能的,我们需要四个字节)。
The following code snippet shows you how to get the address of a boolean variable and how to convert that pointer to an int
(converting to byte
is not possible, we need four bytes).
unsafe
{
// get pointer to boolean
bool* boolptr = &mybool;
// get the int ptr (not necessary though, but makes following easier)
int* intptr = (int*)boolptr;
// get value the pointer is pointing at
int myint = *intptr;
// get the address as a normal integer
int myptraddress = (int) intptr;
}
您说的理想商店4字节位。除非你有一个4位的机器架构,我强烈反对意见,因为它会使检索和存储的布尔值很慢。但更重要的是:你在这里谈论C#,而不是C ++。 C#势必其中指出一个布尔被存储为字节,并且每个存储器地址是长在32位体系结构,这意味着指针是四个字节长四个字节的CLR。因此,你的问题,一个bool *转换(指针布尔)别的东西只能转换为整数或其他数据类型,它是宽4个字节。
you say "ideally store 4 bits in a byte". Unless you have a 4-bits machine architecture, I'd strongly advice against it because it will make retrieving and storing the booleans very slow. But more importantly: you are talking C# here, not C++. C# is bound to the CLR which states that a boolean is stored as a byte and that each memory address is four bytes long in 32 bits architectures, which means pointers are four bytes long. Hence, your question, converting a bool* (pointer to a bool) to something else can only be converted into an integer or other datatype that is four bytes wide.
一个技巧:使用标志可以最好地利用空间:这使枚举类型占用一点对于每个标志,它给你八布尔每个字节
A tip: using flags you can utilize space best: this makes enum types take up a bit for each flag, which gives you eight booleans for each byte.
这篇关于在C#中布尔*实用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!