I have a problem with the substr() command, I’m trying to get two different addresses split from one address in an example memory management simulator. In the example below: The LoadParameters function obtains a set of values for VirtualMemSize and PageFrameLength which are used to calculate where the bit string should be split from.
In the example, LoadParameters() stores values for VirtualMemSize and PageFrameLength (20 and 8 respectively.) which are global values. The problem is that the code only works if I type in numbers in place of the parameters. I’ve tried casting the variables to type size_t but with no luck:
int main(void) {
unsigned int VirtPageAddress;
unsigned int PhysPageAddress;
unsigned int OffsetAddress;
LoadParameters();
int VirtualAddress = 0xCAFEF00D;
string pagestring;
// Convert the hex address into a binary string and then
// split it into page index and offset.
string bitstring = bitset<sizeof(VirtualAddress) * 8>
(VirtualAddress).to_string();
cout << dec << VirtualMemSize << endl;
cout << dec << PageFrameLength << endl;
cout << bitstring << endl;
// (Reports: 20, 8 and "11001010111111101111000000001101"
// Extract relevant bits for the Page Index.
pagestring = bitstring.substr((32-VirtualMemSize),PageFrameLength);
// Convert the split string back into a number so that it
// can be manipulated.
VirtPageAddress = bitset<sizeof(pagestring)>
(pagestring).to_ulong();
cout << "0x" << hex << VirtPageAddress << endl;
return 0;
}
Expected value: “0xef”
Output value: “0x0”
The code works as expected when compiled with g++ (after adding a few includes and definitions you left out). What compiler are you using?
Bear in mind that sizeof(pagestring) returns the size of the class, not of the string it contains; I doubt that is what you intended, and will definitely change depending on your compiler/STL implementation. What do you really mean in that template instantiation?