Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2015
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. function decToBin takes integer decimal returns string
  2. local string binary = ""
  3. local integer modulus
  4.  
  5. loop
  6. set modulus = ModuloInteger( decimal, 2 )
  7. set binary = I2S( modulus ) + binary
  8. set decimal = ( decimal - modulus ) / 2
  9. exitwhen decimal == 0
  10. endloop
  11.  
  12. return binary
  13. endfunction
  14.  
  15. function validateBin takes string binary returns boolean
  16. local integer i = 0
  17.  
  18. loop
  19. if ( ( SubString( binary, i, i + 1 ) != "1" ) and ( SubString( binary, i, i + 1 ) != "0" ) ) then
  20. return false
  21. endif
  22. exitwhen i == StringLength( binary ) - 1
  23. i = i + 1
  24. endloop
  25.  
  26. return true
  27. endfunction
  28.  
  29. function binToDec takes string binary returns integer
  30. local integer decimal = 0
  31.  
  32. if ( validateBin( binary ) == true ) then
  33. binary = I2S( S2I( binary ) ) //Отсекаем нули в начале, если таковые имеются
  34. local integer u = StringLength( binary ) - 1;
  35. local integer i = 0;
  36. loop
  37. decimal = decimal + S2I( SubString( binary, i, i + 1 ) ) * R2I( Pow( 2, u ) )
  38. exitwhen i == StringLength( binary ) - 1
  39. i = i + 1
  40. u = u - 1
  41. endloop
  42. endif
  43.  
  44. return decimal
  45. endfunction
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement