In the process of network transmission, it is necessary to convert the numeric value into a type that can be transmitted by the network (such as a string), which requires Ntohs and htons.
Htons: Converts a value to a string (for network transmission).
Ntohs: Converts a string (for network transmission) to a numeric value.
For example, the backend to pass 1 of the length of the package to the front end, the length of 6598, then the number will be converted to the string ' Ab ' htons, the front end received and then converted to the value of Ntohs 6598.
Helpless Lua does not provide such a library, only write it yourself.
function Gethtons (nInt, Nbyte)--nint number, Nbyte converted to bytes
local Szbigendian = "
for i = 1, nByte-1 do
Local nBit = 8 * (nByte-1)
Local number = Math.floor (Nint/math.pow (2, nBit))
nInt = nint-number * NBit
Szbigendian = Szbigendian. String.char (number)
End
Szbigendian = Szbigendian. String.char (NINT)
return Szbigendian
End
function Getntohs (Szbigendian)
local ntotal = 0
for i = 1, String.len (Szbigendian) does
Local char = String.sub (Szbigendian, I, i)
Local number = String.byte (char)
Local nBit = 8 * (String.len (Szbigendian)-i)
ntotal = ntotal + number * MATH.POW (2, NBit)
End
return ntotal
End
"Texas Hold ' Em development record" with LUA implementation Ntohs () and htons ()