- OTS Fans http://www.otsfans.pun.pl/index.php - Funkcje i systemy http://www.otsfans.pun.pl/viewforum.php?id=118 - Systemy liczbowe funkcje konwertujące. http://www.otsfans.pun.pl/viewtopic.php?id=12 |
Wielki Buch - 2011-04-17 05:45:59 |
Autorem Jest Miziak
Kod:math.dth(liczba) -- konwersja liczby w systemie dziesiątkowym do systemu szesnastkowego(zwracany typ string) tonumber(hexString) -- za pomocą prostej funkcji biblioteki standardowej otrzymujemy odwrotne działanie math.dtb(liczba) -- konwersja liczby w systemie dziesiątkowym do systemu dwujkowego(zwracany typ string) math.btd(binString) -- konwersja liczby binarnej w postaci tekstu na liczbę dziesiętną Do functions.lua lub lib/50-function.lua dodajemy: Kod:math.dth = function(decint) local hex, strHex = "0123456789ABCDEF", "" repeat local mod = decint%16+1 strHex = strHex .. hex:sub(mod, mod) decint = math.floor(decint/16) until decint == 0 return "0x" .. strHex:reverse() end math.dtb = function(decint) local binStr = "" repeat local mod = decint%2 binStr = binStr .. (mod ~= 0 and "1" or "0") decint = math.floor(decint/2) until decint == 0 return binStr:reverse() end math.btd = function(binstr) local out = 0 binstr = binstr:reverse() for i=binstr:len(), 1, -1 do out = out + (tonumber(binstr:sub(i,i))*(2^(i-1))) end return out end Przykładowe zastosowanie: Kod:do math.dth = function(decint) local hex, strHex = "0123456789ABCDEF", "" repeat local mod = decint%16+1 strHex = strHex .. hex:sub(mod, mod) decint = math.floor(decint/16) until decint == 0 return "0x" .. strHex:reverse() end math.dtb = function(decint) local binStr = "" repeat local mod = decint%2 binStr = binStr .. (mod ~= 0 and "1" or "0") decint = math.floor(decint/2) until decint == 0 return binStr:reverse() end math.btd = function(binstr) local out = 0 binstr = binstr:reverse() for i=binstr:len(), 1, -1 do out = out + (tonumber(binstr:sub(i,i))*(2^(i-1))) end return out end print("Wybierz system liczbowy:\n1. Binarny(dwujkowy)\n2. Hexadecymalny(szesnastkowy)") local wybor = tonumber(io.read()) print("Podaj liczbę do konwersji:") local liczba = tonumber(io.read()) if(wybor == 1)then local bin = math.dtb(liczba) print(bin) print(math.btd(bin)) else local hex = math.dth(liczba) print(hex) print(tonumber(hex)) Prosty kalkulator typów, jeśli nie używasz linux'a pomińpierwszą linię (#!/usr/bin/env lua). |