JCHub

  • Home
  • Category
    • A/V
    • WebRTC
    • Beauty of Programming
    • Linux
    • Windows
    • Moments of Life
    • Campus Life
  • Reference
    • API Reference
    • Utilities
    • AV Test
    • Doc
  • Message Board
  • About
JCHub
Code as My Sword, Lost in Obsession
  1. Main page
  2. Beauty of Programming
  3. Main content

网络字节转换到本地字节的函数模板

2016年5月28日 1481hotness 0likes 0comments

在做视频文件解析开发时,经常需要进行网络字节到本地字节的转换。在视频文件中,相关数据是以网络字节存储的,比如视频的宽,定义为uint_32类型,读取时我们需要转换为本地字节序才可以得到正确结果。

操作系统自带api可以帮助我们进行字节序的转换,如下所示函数与具体平台无关:

C++
1
2
3
4
u_short htons(u_short hostshort); // 将u_short 类型变量从主机字节顺序转化到TCP/IP网络字节顺序
u_long htonl(u_long hostlong);    // 将u_long 类型变量从主机字节顺序转化到TCP/IP网络字节顺序
u_short ntohs(u_short netshort);  // 将u_short 类型变量从TCP/IP网络字节顺序转化到主机字节顺序
u_long ntohl(u_long netlong);     // 将u_long 类型变量从TCP/IP网络字节顺序转化到主机字节顺序

我们也可以用c++函数模板实现一个,方便使用,我一般都是用自己的函数模板的:

C++
1
2
3
4
5
6
7
8
9
10
11
// 网络字节到小端
template <class T>
T ntole(T num)
{
    T ret = 0;
    unsigned char * p = (unsigned char*)&num;
    for(int i = 0; i < sizeof(T); i++)
        ret |= (p[i] << ((sizeof(T) - i - 1) * 8));
 
    return ret;
}

This article is licensed with Creative Commons Attribution-NonCommercial-No Derivatives 4.0 International License
Tag: C++
Last updated:2016年6月11日

Jeff

管理员——代码为剑,如痴如醉

Tip the author Like
< Last article
Next article >

Comments

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
Cancel

This site uses Akismet to reduce spam. Learn how your comment data is processed.

相关文章
  • MFC自绘带背景颜色标题栏
  • VC++获取本机IP地址
  • FLTK程序编译错误
  • C++实现windows重启
  • Windows下获取当前屏幕分辨率

COPYRIGHT © 2026 jianchihu.net. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang