The size of
bool
values depends on the implementation (the compiler). It might be a single byte or more. Common is the size of an
int
. You can check it by printing
sizeof(bool)
.
Casting a pointer for different types will only work if both types have the same size. But even then you should know what you do (know how to interpret and use the casted data).
You try to print out a single character (use the
*
dereference operator). The value of that character depends here again on the implementation but in most cases it should be zero or one which are both not printable characters.
If you want to print
bool
values you can use I/O manipulators to define what to be printed (false / true or 0 / 1):
cout << std::boolalpha << booleanValue << '\n';
cout << std::noboolalpha << booleanValue << '\n';
If you need a real conversion, you have to create an output array, iterate over the boolean input array, and assign corresponding values:
unsigned char ucOut[8];
char strOut[9];
for (int i = 0, i < 8; i++)
{
ucOut[i] = b[i] ? 1 : 0;
strOut[i] = b[i] ? '1' : '0';
}
strOut[8] = '\0';
std::cout << strOut;
Note that you can use casting inside the loop because that will cast a single value and not an array. But it can be only used for binary values and not for characters to be printed.
[EDIT]
Note also that I have used a
static_cast
. If you use that in your code for the pointers, the compiler will throw an error. Avoid the old C style casting with C++. There is also a C++ cast operator that can cast the pointers from your example. But when using such (reinterpret) it (hopefully) indicates that the writer of the code knows what he is doing there.
[/EDIT]