text_to_number.html
001| """Convert Text to a (big!) Number.
001|
001| Generate the number of some text by treating each byte of
001| the string as a base-256 digit and the text string as a
001| base-256 number consisting of those digits. The generates
001| and returns both the big-endian and little-endian values.
001|
001| Run without command line arguments to see the default
001| ("Python is fun!!") or provide text on the command line.
001| """
002|
003| from sys import argv
004|
005|
006|
007|
008| def text_to_number (text):
009| """\
009| Convert Text to Number.
009|
009| Expects a string and returns a tuple with BE and LE integer values.
009|
009| Generates the value in two ways. Both require converting
009| the character string to a (UTF-8 encoded) byte string.
009|
009| First: "by hand": Split the text string into separate
009| characters treated as the "digits"; generate the
009| appropriate numerical values for each digit; sum the
009| numerical values to get the result.
009|
009| Second: just use int.from_bytes() to directly convert the
009| text to an integer directly from the bytes.
009|
009| Both are expected to generate the same values. The two methods
009| serve to cross-check each other. Only the second results are
009| actually returned.
009| """
010|
011| bs = bytes(text, encoding='utf-8')
012| print(f'{bs} ({type(bs)})')
013| print()
014|
015|
016|
017| ns = list(bs)
018| rs = list(reversed(bs))
019| print(f'{ns = } ({type(ns)})')
020| print(f'{rs = } ({type(rs)})')
021| print()
022|
023|
024|
025| digits_be = [b*pow(256,bx) for bx,b in enumerate(rs)]
026| digits_le = [b*pow(256,bx) for bx,b in enumerate(ns)]
027| print(f'digits (BE) {digits_be[0]} ... {digits_be[-1]} ({type(digits_be)})')
028| print(f'digits (LE) {digits_le[0]} ... {digits_le[-1]} ({type(digits_le)})')
029| print()
030|
031|
032| value_be = sum(digits_be)
033| value_le = sum(digits_le)
034| print(f'value (BE): {value_be:,} ({type(value_be)})')
035| print(f'value (LE): {value_le:,} ({type(value_le)})')
036| print()
037| print()
038|
039|
040| n_be = int.from_bytes(bs, byteorder='big')
041| n_le = int.from_bytes(bs, byteorder='little')
042| print(f'n (BE): {n_be:,} ({type(n_be)})')
043| print(f'n (LE): {n_le:,} ({type(n_le)})')
044| print()
045| print()
046|
047|
048| return (n_be, n_le)
049|
050|
051|
052| if __name__ == '__main__':
053| print(f'running: {argv[0]}')
054| print()
055|
056|
057| text = ' '.join(argv[1:]) if 1 < len(argv) else 'Python is fun!!'
058| print(f'Text: "{text}"')
059| print()
060|
061|
062| be,le = text_to_number(text)
063| print(f'BE: {be} ({len(str(be))} digits)')
064| print(f'LE: {le} ({len(str(le))} digits)')
065| print()
066|
067| """eof"""
068|