{* *}
code teams

Endian Swap



Big-Endian means that the most significant byte of any multibyte data field is stored at the lowest memory address, which is also the address of the larger field - network byte order.

Little-Endian means that the least significant byte of any multibyte data field is stored at the lowest memory address, which is also the address of the larger field. - host byte order.

C Library Functions

Include the inet.h file to use these functions.

ntohs network byte order to host byte order 16 bit
ntohl network byte order to host byte order 32 bit
htons host byte order to network byte order 16 bit
htonl host byte order to network byte order 32 bit

Other Functions
/* 2 byte signed integers   */
void swap_short_2(short *tni2)
{
    *tni2=(((*tni2>>8)&0xff) | ((*tni2&0xff)<<8));  
}

/* 2 byte unsigned integers */
void swap_u_short_2(unsigned short *tni2)
{
    *tni2=(((*tni2>>8)&0xff) | ((*tni2&0xff)<<8));  
}

/* 4 byte signed integers   */
void swap_int_4(int *tni4)
{
    *tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
           ((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));  
}

/* 4 byte unsigned integers */
void swap_u_int_4(unsigned int *tni4)
{
    *tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
           ((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));  
}

/* 4 byte signed long integers */
void swap_long_4(long *tni4)
{
    *tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
           ((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));  
}

/* 4 byte unsigned long integers */
void swap_u_long_4(unsigned long *tni4)
{
    *tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
           ((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));  
}

/* 4 byte floating point numbers */
void swap_float_4(float *tnf4)
{
    int *tni4=(int *)tnf4;
    *tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
           ((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));  
}

/* 8 byte double numbers */
void swap_double_8(double *tndd8)
{
    char *tnd8=(char *)tndd8;
    char tnc;

    tnc=*tnd8;
    *tnd8=*(tnd8+7);
    *(tnd8+7)=tnc;

    tnc=*(tnd8+1);
    *(tnd8+1)=*(tnd8+6);
    *(tnd8+6)=tnc;

    tnc=*(tnd8+2);
    *(tnd8+2)=*(tnd8+5);
    *(tnd8+5)=tnc;

    tnc=*(tnd8+3);
    *(tnd8+3)=*(tnd8+4);
    *(tnd8+4)=tnc;
}