log_encode.sf 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/ruby
  2. # Author: Trizen
  3. # Date: 02 April 2022
  4. # https://github.com/trizen
  5. # Encode data, using logarithms of integers.
  6. # Example:
  7. # Let's say we want to encode the bytes "abc" == [97, 98, 99]
  8. # We try to find an integer n such that log(n) contains '097098099' after the decimal point.
  9. # One such integer is 1453293358, which gives log(1453293358) = 21.097098099...
  10. # Usage:
  11. # sidef script.sf [input_file]
  12. # The script generates a valid Sidef script as output, such that, when executed, it will produce the input data.
  13. define (
  14. PERL_CODE = false # true to generate Perl code
  15. SLICE_SIZE = 1 # how many bytes to encode into an integer
  16. )
  17. func log_encode(bytes) {
  18. var v = bytes.map { '%03d' % _ }.join
  19. for n in (10 .. 99) {
  20. var t = Num("#{n}.#{v}").exp.round
  21. if (t.log.to_s.substr(3).begins_with(v)) {
  22. return t
  23. }
  24. }
  25. return nil
  26. }
  27. var text = File(ARGV[0] \\ __FILE__).read
  28. var values = []
  29. text.bytes.each_slice(SLICE_SIZE, {|*slice|
  30. while (slice.len != SLICE_SIZE) {
  31. slice += ' '.ord
  32. }
  33. values << log_encode(slice)
  34. })
  35. if (PERL_CODE) {
  36. print %Q'print pack("C#{SLICE_SIZE}", unpack("x3(a3)#{SLICE_SIZE}", log)) for qw('
  37. print values.join(' ')
  38. say ')'
  39. }
  40. else {
  41. print 'STDOUT.binmode(":raw");%n['
  42. print values.join(' ')
  43. say %Q'].each { pack("C#{SLICE_SIZE}", unpack("x3(a3)#{SLICE_SIZE}", .log)).print }'
  44. }