ints as byte representation

10 views
Skip to first unread message

Wes Chow

unread,
Jul 17, 2015, 3:29:50 PM7/17/15
to lu...@googlegroups.com
I'm writing some networking code and would like to send an int as a sequence of binary bytes (not as a string). A socket:write(25) call appears to send the string '25'. In regular Lua I would use the struct module to convert 25 into bytes and then send that, however it seems as if many of the standard libraries don't exist with luvit. What's a poor engineer to do?

Thanks,
Wes

Tim Caswell

unread,
Jul 17, 2015, 4:20:08 PM7/17/15
to lu...@googlegroups.com
The libuv bindings assume all input is a lua string since lua strings are binary safe (they are just arrays of 8-bit data, nothing more).

If you want to send the single int8_t 25, you can do it with "\25" or "\x19" or string.char(25).  If you want larger integers you can either encode them by hand using the bit library or use luajit's ffi structs.

For example, here is encoding a 32-bit integer as 4 bytes https://github.com/creationix/msgpack-lua/blob/master/msgpack.lua#L27-L33

--
You received this message because you are subscribed to the Google Groups "luvit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to luvit+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Wes Chow

unread,
Jul 17, 2015, 4:29:24 PM7/17/15
to lu...@googlegroups.com
write32 is perfect for my needs, thanks, and I was about to look for a msgpack implementation for luvit too!

Wes


You received this message because you are subscribed to a topic in the Google Groups "luvit" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/luvit/9E6tn59BNf0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to luvit+un...@googlegroups.com.

Tim Caswell

unread,
Jul 17, 2015, 4:56:41 PM7/17/15
to lu...@googlegroups.com
By the way, there is a built-in Buffer class in luvit that ports most the node.js Buffer methods including read/write of integers of various sizes.  It works on mutable buffers instead of strings, but the buffers should convert to strings properly when passing them to libuv APIs.

Wes Chow

unread,
Jul 17, 2015, 6:03:42 PM7/17/15
to lu...@googlegroups.com

Hm interesting, that might be what I want to use. I’m building a custom network messaging system at the moment and basically want to be sending datagrams over tcp. I was shooting for the most basic strategy of sending a uint32 of data size, and then a sequence of bytes of that amount of data. Buffer looks like it will work for that.

Wes

Ryan Phillips

unread,
Jul 17, 2015, 6:07:10 PM7/17/15
to lu...@googlegroups.com, wes....@gmail.com
Tim wrote a fast msgpack implementation in luajit as well:
 
Reply all
Reply to author
Forward
0 new messages