The htonl() function in Python

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
# from host order to network order using the 
# function socket.htonl()

import struct
import socket
import sys

# Endianness of the host platform
print("The host system runs on %s endian platform"%sys.byteorder)

# Number to be converted
#num = 1022
num = 1048572
print("Number to convert: 0x%X"%num)

# Print in big endian
beBytes     = struct.pack("!I", num)
print("In big endian format - output of struct.pack():%s"%beBytes)

beBytes1     = num.to_bytes(4, byteorder = 'big')
print("In big endian format - output of to_bytes:%s"%beBytes1)

# Print in little endian
leBytes     = struct.pack("I", num)
print("In little endian format - output from struct.pack():%s"%leBytes)

leBytes1     = num.to_bytes(4, byteorder = 'little')
print("In little endian format - output from to_bytes():%s"%leBytes1)

# Reconstruct the number from big endian
netNumber = int.from_bytes(beBytes1, 'big')   
print("Reconstructed from big endian order: %d"%netNumber)

# Reconstruct the number from little endian
netNumber = int.from_bytes(leBytes1, 'little')   
print("Reconstructed from little endian order: %d"%netNumber)

# Now...convert the number to network byte order
nw = socket.htonl(num)
print("Integer after convertion using htonl():")
print(nw)

# Print the translated integer as bytes...the translated integer is
# also stored in little endian (as host is little endian)
nwOrder = nw.to_bytes(4, byteorder = 'little')
print("Output of htonl:%s"%nwOrder)

# Reconstruct from bytes
print(int.from_bytes(nwOrder, 'little')

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

 


Copyright 2024 © pythontic.com