"Texas Hold ' Em development record" with LUA implementation Ntohs () and htons ()

Source: Internet
Author: User
Tags htons

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.