Decimal Binary

Convert decimal to binary and back using vanilla AppleScript.

OS version: Any

--> SAMPLE USAGE

BintoDec("0101") --> 5


--> now, first parameter is an integer to transform to binary
--> the second parameter, one of 1, 4, 8 or 16, the range of
--> the returned binary digits: bit, nibble, byte or word
DectoBin(result, 8)
--> "00000101"

on BintoDec(n)
	set n to reverse of (n as text)'s text items
	set dec to 0
	set basex to 0
	repeat with i in n
		if i's contents = "1" then
			set dec to dec + (2 ^ basex)
		end if
		set basex to basex + 1
	end repeat
	dec
end BintoDec

on DectoBin(n, range)
	set bin to {}
	repeat while n ? 1
		if (n mod 2) = 0 then
			set beginning of bin to "0"
		else
			set beginning of bin to "1"
		end if
		set n to n div 2
	end repeat
	set bin to "1" & bin
	
	-- range 16 = word
	-- range 8 = byte
	-- range 4 = nibble
	-- range 1 = bit
	
	set binlength to (bin's length) mod range
	if binlength ? 0 then
		set l to range - binlength
		repeat l times
			set bin to "0" & bin
		end repeat
	end if
	bin
end DectoBin

property |version| : 1.0
property author : "Pescados Software ยท [url=http://homepage.mac.com/julifos/soft"]http://homepage.mac.com/julifos/soft"[/url]
property |date| : date "domingo, 21 marzo 2004 17:46:58"
property license : "freeware, open-source"