Judging whether the equality between random strings is a common skill in programming, in the C + + ERA, we can achieve relatively efficient string comparisons by converting each four byte in a string to an int object and comparing four characters at a time through an int object. So, can this idea be implemented in C #? The answer is yes.
Using the above ideas in C #, you have to solve two problems, one of which is to use pointers in C #, and the location of the managed variables that the pointer points to cannot be reassigned by the GC. Second, the corresponding relationship between the managed string and int or long in memory.
Many articles have described in detail the use of pointers in C # method, this article no longer detailed, the way to open the unsafe switch, right-click the solution directory--Select Properties--and then the Build dialog box to choose the "Allow unsafe code" option, so that C # The area where the pointer can be used by the UNSAFE keyword tag is available. We know that the managed variables are randomly allocated, reclaimed, and resized in memory by the system, so pointers to managed variables may point to the wrong area because managed variables are randomly adjusted. To ensure that the pointer can point to the same managed variable throughout, C # provides a fixed statement to complete the task. A pointer that is marked with a fixed, and the amount of the pointing change from start to finish in the area marked by the fixed, and the system does not adjust and redistribute the managed variable. The code is as follows:
string str="Hello World!";
unsafe
{
fixed (char* ps = str)
{
//该区域中ps始终指向托管字符串str
}
}
Using sizeof to measure that long in C # occupies 8 bytes, what is the result if the first 8 bytes of PS are converted to long in the above code? We use the following code to test:
long n=0;
long nLow = 0, nHigh = 0;
string str = "Hello World!";
unsafe
{
fixed (char* ps = str)
{
char* psTemp = ps;
n=*(long*)psTemp;
nLow = n & 0xFFFF; //取最后两个字节
nHigh = (n >> 16) & 0xFFFF; //取第3,4个字节
MessageBox.Show(((char)nLow).ToString() + " " + ((char)nHigh).ToString());
nLow = (n >> 32) & 0xFFFF; //取第5,6个字节
nHigh = (n >> 48) & 0xFFFF; //取第7,8个字节
MessageBox.Show(((char)nLow).ToString() + " " + ((char)nHigh).ToString());
}
}