user5580610
user5580610

Reputation:

How to get the bytes that an unsigned integer is composed of?

Supposing I've this number:

local uint = 2000;

how can I get the bytes that it's composed of? For instance:

print(sepbytes(uint));
-- 7, 208

My try:

local function sepbytes(cur)
  local t = {};
  repeat
    cur = cur / 16;
    table.insert(t, 1, cur);
  until cur <= 0
  return table.unpack(t);
end

print(sepbytes(2000));

This results in:

0   9.8813129168249e-324, +(lots of numbers)...

Expected result:

7, 208

Upvotes: 3

Views: 1729

Answers (1)

user5580610
user5580610

Reputation:

Basing in the comments, if I want 2 fixed bytes (that's the current case), I may use @ajcr solution:

local function InParts(num)
    return ((num & (0xff << 8)) >> 8), (num & 0xff);
end

@EgorSkriptunoff (Lua 5.3) solution works for any amount of bytes.

local function InParts(num)
    return string.pack(">I2", uint):byte(1, -1);
end

Upvotes: 1

Related Questions