Home > LinkedIn, Lua, Programmazione > Conversione da numero decimale in binario in Lua (tobinary())…

Conversione da numero decimale in binario in Lua (tobinary())…

Dal momento che mi serviva una funzione Lua per convertire un numero da binario a decimale (leggi: convertire le triplette di un IP in formato binario) e non l’ho trovata (la tonumber(numero, 2) non fa quello che vorrei), me la sono scritta.

Magari torna utile a qualcuno…

Il codice è estremamente compatto e si basa sull’algoritmo “Binary Swop Method” di Marco Lovatto.

Ne ho scritte due versioni: la prima richiede di specificare il numero di cifre (sequenza di zeri e uni) per il numero binario finale, mentre la seconda fa da sè…

Il codice

--[[

  FILE:    tobinary.lua
  AUTHOR:  Gian Paolo "JP" Ghilardi
  LICENSE: released under the terms of GPL v2.0 ("only")
  PURPOSE: simple tobinary() function
  VERSION: 1.0

  TESTED ON:
  - Lua 5.1.3 on Windows XP SP2, x86 32-bit
  - Lua 5.1 on MacOSX 10.5.8, PPC 32-bit

  REFERENCES:
  [1]: http://knol.google.com/k/marco-lovatto/the-binary-swop-method-reconstructed/1tljxpwlyqs0g/2#
  [2]: http://lua-users.org/lists/lua-l/2006-04/msg00579.html

  ]]--

-- converts a number from decimal notation to binary notation
-- @param number is the number to be converted
-- @figures the number of figures (sequence of 0s and 1s) to be used during the conversion
-- @return the number converted in binary format
function tobinary(number, figures) -- based on [1]
	local ret = ""
	for i = 1, figures do
		-- math.abs => just necessary on MacOSX for a strange "negative zero" bug [2]
		ret = ret .. math.abs(math.floor(number / math.pow(2, figures - i)) % 2)
	end
	return ret
end

-- converts a number from decimal notation to binary notation. It uses the
-- minimal number of figures (sequence of 0s and 1s) required by this task.
-- @param number is the number to be converted
-- @return the number converted in binary format
function tobinary2(number) -- based on [1]
	local ret = ""
	local i = 0		

	while true do
		v = math.floor(number / math.pow(2, i))
		if v < 1 then break end
		v = math.abs(v % 2) -- math.abs just necessary con MacOSX for the strange "negative zero" bug
		ret = v .. ret
		i = i + 1
	end

	return ret
end

Il codice dal vivo

Test della tobinary()

print("[TEST: 0 to 255 step 5]")
for i = 0, 255, 5 do
	print(i .. " => " .. tobinary(i, 10))
end

Lua tobinary()

… e test della tobinary2()

print("[TEST: 0 to 255 step 5]")
for i = 0, 255, 5 do
	print(i .. " => " .. tobinary2(i, 10))
end

Lua tobinary2()

  1. Non c’è ancora nessun commento.
  1. No trackbacks yet.