一天一个CRT函数 _swap
来源:互联网 发布:python做数据库 编辑:程序博客网 时间:2024/05/16 07:20
这是Buffer Manipulation中最后一个函数了,和我们STL里所用的swap函数极为相似。看下函数声明:
void _swab( char *src, char *dest, int n );
如果n为奇数,则把src中n字节的数据与dest中n字节的数据相互交换。如果n为偶数,则把src中n-1字节的数据与dest的n-1字节的数据相互交换。
MSDN上还说“_swab is typically used to prepare binary data for transfer to a machine that uses a different byte order.”
看,在网络传输中还是有一定地位的。
1.实现
1:
2: /***
3: *
4: *Purpose:
5: * This routine copys a block of words and swaps the odd and even
6: * bytes. nbytes must be > 0, otherwise nothing is copied. If
7: * nbytes is odd, then only (nbytes-1) bytes are copied.
8: *
9: *Entry:
10: * srcptr = pointer to the source block
11: * dstptr = pointer to the destination block
12: * nbytes = number of bytes to swap
13: *
14: *Returns:
15: * None.
16: *
17: *Exceptions:
18: *
19: ***/
20: template<typename T>
21: void tSwab(T *pSrc, T *pDest, int nBytes)
22: {
23: tChar b1 = _T('/0');
24: tChar b2 = _T('/0');
25:
26: assert(pSrc != NULL);
27: assert(pDest != NULL);
28: assert(nBytes >= 0);
29:
30: while( nBytes > 1 )
31: {
32: b1 = *pSrc++;
33: b2 = *pSrc++;
34: *pDest++ = b2;
35: *pDest++ = b1;
36:
37: nBytes -= 2;
38: }
39: }
看来还是用到了中间变量,而且还是俩!
2.测试
1: volatile tChar from[] = _T("BADCFEHGJILKNMPORQTSVUXWZYBADCFEHGJILKNMPORQTSVUXWZY");
2: volatile tChar to[] = _T("....................................................");
3:
4:
5: volatile const DWORD dwCount = 10000000;
6: int nSize = sizeof( from ) / sizeof(from[0]);
7:
8: DWORD dwLast = 0;
9: {
10: CCYPerformance timer(dwLast);
11: for(DWORD i = 0; i < dwCount; ++i)
12: {
13: CY_CRT::tSwab(from, to, nSize);
14: }
15: }
16: cout << dwLast << endl;
17:
18: dwLast = 0;
19: {
20: CCYPerformance timer(dwLast);
21: for(DWORD i = 0; i < dwCount; ++i)
22: {
23: ::_swab((char *)from, (char *)to, nSize);
24: }
25: }
26: cout << dwLast << endl;
结果:
- 一天一个CRT函数 _swap
- 一天一个CRT函数 _memccpy
- 一天一个CRT函数 memchr
- 一天一个CRT函数 memcmp
- 一天一个CRT函数 memcpy
- 一天一个CRT函数 _memicmp
- 一天一个CRT函数 memmove
- 一天一个CRT函数 memset
- 一天一个CRT函数 atof
- 一天一个CRT函数 atoi
- 一天一个CRT函数 strcoll
- 一天一个CRT函数 _strdec
- 一天一个CRT函数 strchr
- 一天一个CRT函数 strcspn
- 一天一个CRT函数 _strdup
- 一天一个CRT函数 strpbrk
- 一天一个CRT函数 strcspn
- 一天一个CRT函数 strrev
- LPVOID浅谈
- JSP Tag Files 技术总结
- 基于策略的通用资源池
- 反转你的脑
- python核心编程2版 学习笔记
- 一天一个CRT函数 _swap
- 设计模式学习----Builder模式
- 在线学习 shell 的地方
- 数据库修改表
- this 访问
- 上网本的冲动?
- HEX文件格式,ihex,hex解析
- 关于oracle存储过程调用问题。execute method error : DataAccessException,或者时参数个数或类型错误,等等
- TreeListView学习应用(一)