Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to ensure 4-byte alignment when converting a byte pointer to an integer pointer?
How to ensure 4-byte alignment when converting a byte pointer to an integer pointer?

The byte pointer points to whatever it is, and there is no way to align it.

For example, a piece of memory like this:

0x12340000 41 42 43 44 45 46 47 48< /p>

0x12340008 49 4a 4b 4c 4d 4e 4f 00

If char* p = (char*) 0x12340000; that is, p represents "ABCDEFGHIJKLMNO"

Now let char* p2 = p1 + 7; i.e. 0x12340007

Then int* p3 = (int*) p2; then using *p3 to access memory will cause inefficiency or errors (if the operating system has not been set in advance to allow it to automatically If you read multiple times to obtain non-aligned data, you may even get an error directly)

So what do you have to do? Do you want the value of p3 to be 0x12340004?

int* p3 = (int*) ((unsigned int)p2 & ~3); //Erase all 1s in the last two digits

In this way, p3 is 0x12340004