Posts

Showing posts from September, 2022

Identify machine is little or big endian

int a = 0x01346283;     This is 32 bit machine.  int data type is 4 byte in memory it is allocated as below in little endian 1001     1002     1003     1004 83          62          34            01     in big endian 1001    1002    1003    1004 01          34            62          83 int main() {     int a = 1;     char *b = (char *)&a;     if(*b)          then its little endian } To convert one endian to other, write macro which does left shift each byte and OR it for ex: int x = 0x12345678 from little endian to big endian 78 << 0 | 56 << 8 | 34 << 16 | 12 << 24 from big endian to little endina 12 << 0 | 34 << 8 | 56 << 16 | 78 << 24

Implementation of C lib ntohl()

  Thus, only the byte order of the network matters, and the network is big-endian: and host can be little or big endian Intel x86 is little endian # include <stdint.h> # include <string.h> uint32_t ntohl ( uint32_t const net) { uint8_t data[ 4 ] = {}; memcpy (&data, &net, sizeof (data)); return (( uint32_t ) data[ 3 ] << 0 ) | (( uint32_t ) data[ 2 ] << 8 ) | (( uint32_t ) data[ 1 ] << 16 ) | (( uint32_t ) data[ 0 ] << 24 ); }