C++ also has a primitive data type called Wide Character (wchar_t) for storing a larger variety of characters. This time, we use up 4 bytes of storage to store a Unicode value instead.
wchar_t pi = L'π';
The wchar_t
part reserves 2 or 4 bytes of memory (depends on compiler) to store a Unicode Value
The pi
part associates the address of the memory we just allocated to the variable name
The L'π'
part converts the pi symbol into it's Unicode value, and stores than number as binary into the memory location:
This is 960, so 960 gets converted into binary and stored into our memory:
960 in binary = 1111000000
http://www.tamasoft.co.jp/en/general-info/unicode-decimal.html
When we reference pi
like this:
std::wcout << pi
Note that wcout is used for printing wide characters.
The program looks at the memory address associated with pi
and then reads in the binary values from 2 or 4 bytes. It then finds the character associated with that Unicode value (960 = π ), and then displays this into the terminal. Note that if the symbol isn't supported by your locale, nothing will be printed.
#include <iostream>
/* Prints Contents of Memory Blocks */
static void print_bytes(const void *object, size_t size){
#ifdef __cplusplus
const unsigned char * const bytes = static_cast<const unsigned char *>(object);
#else // __cplusplus
const unsigned char * const bytes = object;
#endif // __cplusplus
size_t i;
printf("[-");
for(i = 0; i < size; i++)
{
//printf(bytes[i]);
int binary[8];
for(int n = 0; n < 8; n++){
binary[7-n] = (bytes[size -1 - i] >> n) & 1;
}
/* print result */
for(int n = 0; n < 8; n++){
printf("%d", binary[n]);
}
printf("%c", '-');
}
printf("]\\n\\n");
}
int main () {
std::cout << "\\nStoring a Wide Char in Memory";
std::cout << "\\n------------------------\\n\\n";
wchar_t pi = L'π';
std::cout << "Address is "<< static_cast<void *>(&pi) << "\\n\\n";
std::cout << "Size is "<< sizeof(pi) << " bytes\\n\\n";
std::wcout << "Value is " << pi << "\\n\\n";
std::cout << "\\nMemory Blocks : \\n";
print_bytes(&pi, sizeof(pi));
return 0;
}
This program stores and retrieves a wide char and prints its size, address, value and memory: