Cezar Filho
Cezar Filho

Reputation: 41

How to convert a number to signed/unsigned 16/32 bits?

Okay, so I need to send signed/unsigned 16/32 bits integers using udp. How do I convert a Lua number to these types so I can write it byte by byte. I have access to bitwise operators.

I've searched this question thoroughly but I only found one function that didn't work with signed.

I couldn't even find any material explaining how to do this, so if someone could link me something, I'd be extremely grateful.

Upvotes: 4

Views: 9905

Answers (1)

Doug Currie
Doug Currie

Reputation: 41170

If your Lua numbers are in the range of the type you are writing, then there is no conversion necessary. You just need to extract the bytes and write them.

Assuming big endian (network order), and Lua 5.3:

local b16H = (x >> 8) & 0xff;
local b16L = (x     ) & 0xff;
my_output(string.char(b16H, b16L));

This works for signed as well as unsigned.

For 32 bits

local b32HH = (x >> 24) & 0xff;
local b32HL = (x >> 16) & 0xff;
local b32LH = (x >>  8) & 0xff;
local b32LL = (x      ) & 0xff;
my_output(string.char(b32HH, b32HL, b32LH, b32LL));

Upvotes: 6

Related Questions