simulation of Htonl, Ntohl, htons, ntohs function Implementation
2010-04-14 17:25:06| Category: Network Programming | Tags: | font size Big Small subscription from:http://wxxweb.blog.163.com | Author:wxxweb | E-mail:wxxweb@163.com
This article can be reproduced arbitrarily, but please indicate the source of the original in the network today, such as the discussion of htonl, Ntohl in different machine differences, deliberately simulated htonl, Ntohl, htons, ntohs function implementation.
The implementation is as follows:
typedef unsigned short int uint16;
typedef unsigned long int uint32;
Short-integer-size-end interchange
#define BIGLITTLESWAP16 (A) (((UInt16) (a) & 0xff00) >> 8) |
(((UInt16) (A) & 0X00FF) << 8))
Long Integer size End interchange
#define BIGLITTLESWAP32 (A) (((UInt32) (a) & 0xff000000) >> 24) |
(((UInt32) (A) & 0x00ff0000) >> 8) | \
(((UInt32) (A) & 0x0000ff00) << 8) | \
(((UInt32) (A) & 0x000000ff) << 24))
Native big end returns 1, small side returns 0
int Checkcpuendian ()
{
union{
unsigned long int i;
unsigned char s[4];
}c;
C.I. = 0x12345678;
return (0x12 = = C.s[0]);
}
Analog htonl function, native byte sequence to network byte order
unsigned long int htonl (unsigned long int h)
{
Joben is a big-endian, with the network byte sequence, directly return
The Joben is small, converted to a big end and returned
Return Checkcpuendian ()? H:BIGLITTLESWAP32 (h);
}
Analog Ntohl function, network byte sequence to native byte order
unsigned long int ntohl (unsigned long int n)
{
Joben is a big-endian, with the network byte sequence, directly return
Joben is small, network data is converted to small end and returned
Return Checkcpuendian ()? N:BIGLITTLESWAP32 (n);
}
Analog htons function, native byte sequence to network byte order
unsigned short int HtoNs (unsigned short int h)
{
Joben is a big-endian, with the network byte sequence, directly return
The Joben is small, converted to a big end and returned
Return Checkcpuendian ()? H:BIGLITTLESWAP16 (h);
}
Analog Ntohs function, network byte sequence to native byte order
unsigned short int ntohs (unsigned short int n)
{
Joben is a big-endian, with the network byte sequence, directly return
Joben is small, network data is converted to small end and returned
Return Checkcpuendian ()? N:BIGLITTLESWAP16 (n);
}