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.
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).
EDIT: (because you edited your q.)
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;
}
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.