Advertisement
Sporkinator

dec_to_any()

Mar 14th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     Script Name: dec_to_any
  3.     Original Creator: ragarnak
  4.     Use: dec_to_any(real, string)
  5.     Arg0: Real decimal value greater than or equal to 0 to convert.
  6.    
  7.     Arg1: String set of symbols to use for conversion.
  8.    
  9.     Examples:
  10.     "01" for BINARY
  11.     "0123456789ABCDEF" for HEX
  12.     "01234567" for OCTAL
  13.     etc.
  14.    
  15.     Modified By: Big J/Sporkinator
  16.    
  17.     Fixed the problem of
  18.     infinite loops when passing
  19.     negative numbers, and added
  20.     some checks to prevent
  21.     unexpected errors.
  22.     Also, instead of flooring,
  23.     used truncation.
  24. */
  25. show_debug_message("dec_to_any(" + string(argument0) + ", " + argument1 + ")");
  26. var base, num, result, error, str;
  27. error = ""
  28. if (is_real(argument0))
  29. {
  30.     num = argument0 - frac(argument0); //Truncate the number
  31. }
  32. else
  33. {
  34.     show_error("First argument to dec_to_any() must be a real.", false);
  35.     return error;
  36. }
  37. if (num < 0) //Prevent infinite loop
  38. {
  39.     show_error("dec_to_any() cannot handle negative values.", false);
  40.     return error;
  41. }
  42. str = argument1;
  43. if (is_real(str)) //Prevent symbol set being passed as real
  44. {
  45.     show_error("Second argument to dec_to_any() must be a string.", false);
  46.     return error;
  47. }
  48. base = string_length(str); //Determine base
  49. result = "";
  50. do
  51. {
  52.     result = string_char_at(str, 1 + (num mod base)) + result;
  53.     show_debug_message("Num = " + string(num) + " mod [Base " + string(base) + "] " + string(num mod base) + " Character Added: " + string_char_at(str, 1 + (num mod base)));
  54.     show_debug_message(string(result));
  55.     //num = num div base; //The "div" operator buggy and can have unexpected results!
  56.     num /= base;
  57.     num -= frac(num);
  58. }
  59. until (num == 0);
  60. return result;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement