--[[ Eugeniy Mikhailov 1 June 2021 ]] ------------ BITS TO DECIMAL ------------ function toNum(bits) local n = 0; local m = 1 -- m represents power of 2 for i = 1, #bits do -- '#' indicates number of bits in variable n = n + bits[i]*m m = m*2 end return n end ------------ DECIMAL TO BIT ------------ -- ****NOTE: Suitable only for positive integer inputs**** -- continue to divide by two until quotient is zero function toBits(num) local t = {} local cnt = 0 while num > 0 do cnt = cnt + 1 remainder = num % 2 -- Basics of binary. If num is divisible by two, 0 in table. If not, 1 in table t[cnt] = remainder -- defaults to #t+1 key num = (num - remainder)/2 --num = math.floor((num - remainder)/2) -- carry out calculation -- note math.floor used here to eliminate floating values --we subtract the number with the binary bit found, then divide by two to find the next bit end return t end ------------ BINARY SEPARATION TO STRING ------------ function bin2string(bTable, separator) if nil == separator then separator="" end local str="" for i=#bTable,1,-1 do if (i % 8) == 0 then str=str..separator end -- space between every 8 bits if bTable[i] == 0 -- to take care of floats then str=str.."0" else str=str.."1" -- assumes only nonzeros are ones -- if nonzeros/ones involved, will also be counted as ones here end end return str end ------------ TESTS FOR bin2string------------ if "11111110" ~= bin2string(toBits(254)) then print("Error in bits conversion") end if 2376 ~= toNum(toBits(2376)) then print("Error in bits conversion") end ------------ SLICE STRING ------------ function bitSlice(bTable, low, high) -- make sure that 1 <= low <= high local slice={} local cnt=1 --counter for i=low,high do slice[cnt] = (bTable[i]) cnt = cnt+1 end return slice end ------------ TESTS FOR bitSlice ------------ if "345" ~= table.concat(bitSlice({1,2,3,4,5,6,7,8}, 3,5)) then print("Error bitSlice is compromised") end ------------ COPY TABLE ------------ -- issue with index naming in future table. function copyTableArray(src) local dst={} for i=1,#src do dst[i] = (src[i]) end return dst end ------------ COMBINE SLICES ------------ function tableReplace(bTable1, bTable2, low, high) -- low=first index, high=last index local dest = copyTableArray(bTable1) local cnt=1 for i=low,high do dest[i]=(bTable2[cnt]) cnt = cnt + 1 end return dest -- destination end ------------ PAD ZEROS INTO EMPTY INDICES ------------ function pad2NumBitsInPlace(bTable, num) for i= #bTable+1, num do bTable[i]=0 end return bTable end ------------ TEST PAD ZEROS ------------ if "00010111" ~= bin2string(pad2NumBitsInPlace({1,1,1,0,1},8)) then print("Error in pad2NumBitsInPlace") end