This is C++ code for reading traces of address of main memory for cache memory simulation:
char hex[20];
ifstream infile;
infile.open(filename,ios::in);
if(!infile) {
cout<<"Error! File not found...";
exit(0);
}
int set, tag, found;
while(!infile.eof()) { //Reading each address from trace file
if(base!=10) {
infile>>hex;
address = changebase(hex, base);
} else {
infile>>address;
}
set = (address / block_size) % no_set;
tag = address / (block_size * no_set);
}
I have converted this to C# code:
char[] hex = new char[20];
FileStream infile=new FileStream(filename, FileMode.Open);
if (infile == null) {
Console.Write("Error! File not found...");
Environment.Exit(0);
}
int set;
int tag;
int found;
while (!infile.CanRead) { //Reading each address from trace file
if (@base != 10) {
infile >> hex;
address = changebase(hex, @base);
} else {
infile >> address;
}
set = (address / block_size) % no_set;
tag = address / (block_size * no_set);
}
The problem is on line infile >> hex;
C# is giving syntax errors, as shift right operator cannot be applied to string operators.
Why this is not working? I'm making a small cache hit and miss calculation project.
To quantify what Eric means:
C++ is quite flexible in the operators that can be overloaded. It has become an "idiom" that the bitshift operators <<
and >>
also be used for input and output. This actually makes kind of sense as it is a logical construct and the eye registers some kind of "flow" between objects.
In C#, you don't overload those operators. What Eric means is, you need to say explicitly, on a stream object, to write (or indeed, read) something. This means calling the methods directly.
In essence you're doing the same thing - the operator overloading is just a nice shortcut, but at the end of the day some method is going to be called - be it a nice decorative "operator overload" or a plain old function call with a name.
So, in C++ we might write:
std::cout << "Hello" << std::endl;
Whereas in C# we'd write:
Console.WriteLine("Hello");
If we ignore the fact that std::cout
could potentially be different from the console window (this is illustrative), the concept is exactly the same.
To expand on the idea of the operators, you'll also have probably come across things such as stringstream
.. a class that acts like a stream for strings. It's really quite useful:
std::stringstream ss;
int age = 25;
ss << "So you must be " << age << " years old.";
In C#, we achieve this with the StringBuilder
class:
StringBuilder sb = new StringBuilder();
int age = 25;
sb.Append("So you must be ").Append(age).Append(" years old");
They both do exactly the same thing. We could also do:
sb.AppendFormat("So you must be {0} years old", age);
This is more akin (in my opinion) to the more C-like sprintf
methods, or more recently, boost's format library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With