Hex, Decimal conversion

From Director Online Wiki
Jump to: navigation, search
---------------------------------------------
--Hex To Integer conversion
---------------------------------------------
on decToHex decIn,pad
  if (decIn>the maxInteger) or (decIn<0) then 
    return -1
  end if
  hexStr="0123456789ABCDEF"
  startMult=0
  tempDec=decIn
  repeat while tempDec>=16
    tempDec=tempDec/16
    startMult=startMult+1
  end repeat
  doMult=integer(power(16,startMult))
  --now we have the starting multiplier
  hex=""
  tempDec=decIn
  repeat while doMult>1
    curHex=tempDec/doMult
    hexChar=hexStr.char[curHex+1]
    hex=hex&hexChar
    tempDec=tempDec-(doMult*curHex)
    doMult=doMult/16
  end repeat
  hexChar=hexStr.char[tempDec+1]
  hex=hex&hexChar
  if pad then
    if hex.length<4 then
      repeat while hex.length<4
        hex="0"&hex
      end repeat
    else
      if hex.length<8 and hex.length>4 then
        repeat while hex.length<8
          hex="0"&hex
        end repeat
      end if
    end if
  end if
  return hex
end
 
---------------------------------------------
--Hex To Integer conversion
---------------------------------------------
on hexToDec  hexIn
  hexStr="0123456789ABCDEF"
  mult=1
  curDec=0
  hexLength=hexIn.length
  repeat with cnt=hexLength down to 1
    thisHex=hexIn.char[cnt]
    decValue=offSet(thisHex,hexStr)-1
    decValue=decValue*mult
    curDec=curDec+decValue
    mult=mult*16
  end repeat
  if curDec<0 then return -1
  return curDec
end