Overview:
- The function htonl() of Python socket module converts a 4 byte integer from host byte order to network byte order and returns the result as an integer.
- If the byte order of the host platform is same as the network order the original parameter value is returned without any conversion. Otherwise, htonl() swaps the bytes such that byte[0]= byte[3], byte[1]= byte[2], byte[2]=byte[1], byte[3]=byte[0].
Example:
# Example Python program that converts a 32 bit integer import struct # Endianness of the host platform # Number to be converted # Print in big endian beBytes1 = num.to_bytes(4, byteorder = 'big') # Print in little endian leBytes1 = num.to_bytes(4, byteorder = 'little') # Reconstruct the number from big endian # Reconstruct the number from little endian # Now...convert the number to network byte order # Print the translated integer as bytes...the translated integer is # Reconstruct from bytes |
Output:
The host system runs on little endian platform Number to convert: 0xFFFFC In big endian format - output of struct.pack():b'\x00\x0f\xff\xfc' In big endian format - output of to_bytes:b'\x00\x0f\xff\xfc' In little endian format - output from struct.pack():b'\xfc\xff\x0f\x00' In little endian format - output from to_bytes():b'\xfc\xff\x0f\x00' Reconstructed from big endian order: 1048572 Reconstructed from little endian order: 1048572 Integer after convertion using htonl(): 4244573952 Output of htonl:b'\x00\x0f\xff\xfc' 4244573952 |