The idea is to take a series of numbers and convert them into a series of characters (string) based on assigned bits for each number into one coherent string.
number (bits) = binary = string/character
49 (6 bits) = 110001 = "1"
122 (8 bits) = 01111010 = "z"
122 (16 bits) = 0000000001111010 = "z"
1 (1 bits) = 1 = " "
total (31 bits rounded up to 32 bits) = 'output string' = 0:110001|01111010|0000000001111010|1
One important distinction is I don't want to round the bits of individual items up to an 8 bit factor. Rather I want to round up the WHOLE combined array of bits to neatly fit into a string. As you can see in my above example I am trying to solve 'output string'.
Everything before ':' would be the inserted bits to round out the networked string, the '|' are just for this example.
EDIT: I guess I could just count up from the right for x bits to get the number from binary. However if you have any efficient ideas please let me know.
EDIT-2: Found what I was looking for, here is the basic code for anyone curious.
Code: Select all
function fromBits( s )
return tonumber( s , 2 )
end
function toBits( n )
local s = ""
local b
while ( n > 0 ) do
b = math.fmod( n , 2 )
s = b .. s
n = ( n - b ) / 2
end
return s
end
NOTE: It occurs to me I can cheapen the cost of conversion by storing the converted values for future lookup in the format of [ number] -> 'binary'. Could probably even take it a step further to maximize performance to ridiculous degrees at the cost of memory. (Most computers these days have sufficient memory to allow for such a trade-off)
EDIT-4: Here is the final tobits function that I will likely use.
Code: Select all
function tobits( n , bits )
local n = math.abs( n )
local s = ""
local b
while ( n > 0 ) do
b = math.fmod( n , 2 )
s = b .. s
n = ( n - b ) / 2
end
if ( bits ) then
local l = string.len( s )
if ( l > bits ) then
print( l , bits , l - bits )
return string.sub( s , ( l + 1 ) - bits )
elseif ( l < bits ) then
return string.rep( '0' , bits - l ) .. s
end
end
return s
end