3,881
社区成员
发帖
与我相关
我的任务
分享
Listing 1. Munging data one byte at a time
void Munge8( void *data, uint32_t size ) {
uint8_t *data8 = (uint8_t*) data;
uint8_t *data8End = data8 + size;
while( data8 != data8End ) {
*data8++ = -*data8;
}
}
/×It took an average of 67,364 microseconds to execute this function. Now modify it to work on two bytes at a time instead of one byte at a time -- which will halve the number of memory accesses:×/
Listing 2. Munging data two bytes at a time
void Munge16( void *data, uint32_t size ) {
uint16_t *data16 = (uint16_t*) data;
uint16_t *data16End = data16 + (size >> 1); /* Divide size by 2. */
uint8_t *data8 = (uint8_t*) data16End;
uint8_t *data8End = data8 + (size & 0x00000001); /* Strip upper 31 bits. */
while( data16 != data16End ) {
*data16++ = -*data16;
}
while( data8 != data8End ) {
*data8++ = -*data8;
}
/*This function took 48,765 microseconds to process the same ten-megabyte buffer -- 38% faster than Munge8. However, that buffer was aligned. If the buffer is unaligned, the time required increases to 66,385 microseconds -- about a 27% speed penalty. The following chart illustrates the performance pattern of aligned memory accesses versus unaligned accesses:*/
}
struct tag
{
char ch;
int n;
}
struct tag
{
int n;
char ch;
}
//下面这个简单的代码只是对高位部分在高地址,低位部分在低地址,这就是所谓的小端进行验证
int main()
{
unsigned short sn = 0x1234;
char *p = (char *)&sn;
printf("%p %x, %p %x\n", p, *p, p+1, *(p+1));
return 0;
}