Eozum
Eozum

Reputation: 1

Concat bits into int in LUA

For a project, I need to convert a list of booleans into one int. I already did the concat of the values and I get a binary number with 16 bits :

The boolean values
1

My binary
2

But i now need to convert this binary number into an Int.
For example, this binary should have the value 32.

Is there any way to do this ? Is this even possible ? I hope my explanations were clear.

Thanks !

Upvotes: 0

Views: 158

Answers (1)

koyaanisqatsi
koyaanisqatsi

Reputation: 2793

It is...

€ lua
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
> bin = '0.00.00.00.00.00.00.00.00.00.01.00.00.00.00.00.0'
> bin:gsub('%.0', '')
0000000000100000    16
> tonumber(bin:gsub('%.0', ''), 2)
32

string.gsub() https://www.lua.org/manual/5.4/manual.html#pdf-string.gsub
tonumber() https://www.lua.org/manual/5.4/manual.html#pdf-tonumber

PS: I am curious how you "already did the concat of the values and I get a binary number with 16 bits"
In fact bin has 17 values delimited with 16 dots.

I would do the following...

> bools = {false,false,false,false,false,false,false,false,false,false,true,false,false,false,false,false}
> #bools
16
> for k, v in pairs(bools) do bools[k] = v == true and 1 or 0 end
> table.concat(bools)
0000000000100000
> tonumber(table.concat(bools), 2)
32
-- Convert back to booleans
> for k, v in pairs(bools) do bools[k] = v == 1 and true or false end

Upvotes: 1

Related Questions