Using macros to simulate the implementation of HTONL, Ntohl, htons, Ntohs

Source: Internet
Author: User
Tags htons

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 = {0x12345678};

return (0x12 = = C.s[0]);
}

Analog htonl function, native byte sequence to network byte order
#define HTONL (A) (Checkcpuendian ()? (a): BigLittleSwap32 (a))

Analog Ntohl function, network byte sequence to native byte order
#define NTOHL (a) htonl (a)

Analog htons function, native byte sequence to network byte order
#define HTONS (A) (Checkcpuendian ()? (a): BigLittleSwap16 (a))

Analog Ntohs function, network byte sequence to native byte order
#define NTOHS (a) HtoNs (a)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.