Re: FFI and endian conversion

  • From: Justin Cormack <justin@xxxxxxxxxxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 25 Jul 2012 12:18:46 +0100

On 25 Jul 2012 11:44, "Mike Pall" <mike-1207@xxxxxxxxxx> wrote:

> It's a low-level API, so the magic is limited. But it's easy
> enough to add this functionality yourself:
>   local ffi = require("ffi")
>   local bit = require("bit")
>   local function n32(x) return x end
>   local n16 = n32
>   if ffi.abi("le") then
>     local shr = bit.rshift
>     n32 = bit.bswap
>     function n16(x) return shr(n32(x), 16) end
>   end
> Then use n32(foo.field) or n16(foo.field) to access fields in
> network byte order (aka ntohl or ntohs).

I have been using ffi metatypes to add these accessors so you do not need
to explicitly convert. Eg so x.sin_port is in network byte order but you
can use x.port to get the host byte order using the metatable.

You could also hide any alignment issues using metatables.


Other related posts: