mardi 24 mai 2016

convert to string with and without reinterpret_cast

I have been looking for code to get CPUID in Linux and came across several good examples. These are specific questions between difference in implementation. Below are unsigned integers and it uses reinterpret_cast with size_t as 12

struct CPUVendorID{
unsigned int ebx;
unsigned int edx;
unsigned int ecx;

string toString() const {
    return string(reinterpret_cast<const char *>(this), 12);
}
};
...
CPUVendorID vendorID { .ebx = ebx, .edx = edx, .ecx = ecx };
string vendor = vendorID.toString();

another form of to get the same output with size_t as 4 is given below:

string vendor;
vendor += string((const char *)&cpuID.EBX(), 4);
vendor += string((const char *)&cpuID.EDX(), 4);
vendor += string((const char *)&cpuID.ECX(), 4);
cout << "CPU vendor = " << vendor << endl;

Both output 12 character string. Can someone explain me what is happening in the reinterpret_cast statement above ? I find this way of implementation very elegant, but I don't know why its working obviously 4*3=12. But, how does it manage to concatenate data from the 3 ebx, edx and ecx?

CPU's manufacturer ID string – a twelve-character ASCII string stored in EBX, EDX, ECX (in that order) CPUID wiki

Aucun commentaire:

Enregistrer un commentaire