有没有什么大小端转换的函数或者API?

elemusic 2012-12-11 11:16:37
不知道有没有现成的,或者库也行,总感觉有些东西写完后发现有现成的函数,有就种那啥的感觉。
双字,三字,四字之类的。

另外问一下,用windows api函数ReadFile,把数据读入数组后,得到的是小端数据。
有没有什么函数直接读入就可以选择要大端的数据呢?
...全文
444 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Binzo 2012-12-12
  • 打赏
  • 举报
回复
bitset容器
图灵狗 2012-12-12
  • 打赏
  • 举报
回复

#if defined(BIG_ENDIAN) && !defined(LITTLE_ENDIAN)

   #define htons(A) (A)
   #define htonl(A) (A)
   #define ntohs(A) (A)
   #define ntohl(A) (A)

#elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)

   #define htons(A) ((((uint16_t)(A) & 0xff00) >> 8 ) | \\
                      (((uint16_t)(A) & 0x00ff) << 8 ))
   #define htonl(A) ((((uint32_t)(A) & 0xff000000) >> 24) | \\
                      (((uint32_t)(A) & 0x00ff0000) >> 8 ) | \\
                      (((uint32_t)(A) & 0x0000ff00) << 8 ) | \\
                      (((uint32_t)(A) & 0x000000ff) << 24))
   #define ntohs     htons
   #define ntohl     htohl

#else

   #error Either BIG_ENDIAN or LITTLE_ENDIAN must be #defined, but not both.

#endif
nice_cxf 2012-12-12
  • 打赏
  • 举报
回复
其实就是两个宏定义而已: #define HTONL(v) ( ((v) << 24) | (((v) >> 24) & 255) | (((v) << 8) & 0xff0000) | (((v) >> 8) & 0xff00) ) #define HTONS(v) ( (((v) << 8) & 0xff00) | (((v) >> 8) & 255) )
sjjwind 2012-12-12
  • 打赏
  • 举报
回复
自己写个转换吧,也挺简单的,这样的API没听说过。
sanae 2012-12-12
  • 打赏
  • 举报
回复
其实我个人觉得ReadFile这东西不知道数据的意义,比方说大小端,只是原样读入而已,建议读入之后再加个操作交换字节序
赵4老师 2012-12-12
  • 打赏
  • 举报
回复
htonl The Windows Sockets htonl function converts a u_long from host to TCP/IP network byte order (which is big-endian). u_long htonl ( u_long hostlong ); Parameters hostlong [in] A 32-bit number in host byte order. Remarks The htonl function takes a 32-bit number in host byte order and returns a 32-bit number in the network byte order used in TCP/IP networks. Return Values The htonl function returns the value in TCP/IP's network byte order. QuickInfo Windows NT: Yes Windows: Yes Windows CE: Use version 1.0 and later. Header: Declared in winsock2.h. Import Library: Link with ws2_32.lib. See Also htons, ntohl, ntohs, WSAHtonl, WSAHtons, WSANtohl, WSANtohs
elemusic 2012-12-12
  • 打赏
  • 举报
回复
虽然已经写完了,不过还是散下分吧。

64,687

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧