Skip to content

Instantly share code, notes, and snippets.

@ochaloup
Last active May 23, 2023 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochaloup/87d8745c0aa7797fe1e9dbdfdb01c931 to your computer and use it in GitHub Desktop.
Save ochaloup/87d8745c0aa7797fe1e9dbdfdb01c931 to your computer and use it in GitHub Desktop.
Python script to print unit8 array in string utf8 format or int (it does not care about non utf8 data)
#!~/.pyenv/shims/python3
# Usage
# string: it can only be used with data that are utf8 converible, otherwise error is shown
# toout.py [6,0,0,0,104,101,108,108,111,51]
# Output:
# hello3
# ---
# toout.py [3,0,0,0] int
# Output:
# 3
import sys
import json
import re
import sys
from enum import Enum
OutputType = Enum('OutputType', ['UTF8', 'INT'])
if len(sys.argv) < 2 or len(sys.argv) > 3:
print(f"Expecting one argument of json array listing uint items, and optional argument of decoding type. Provided arguments: '{sys.argv}'")
exit(1)
json_string = sys.argv[1]
json_string = json_string.strip()
convert_to = OutputType.UTF8
if len(sys.argv) == 3:
output_type_arg = sys.argv[2].upper()
if re.match('INT|INTEGER|UINT|NUMBER', output_type_arg):
convert_to = OutputType.INT
if not json_string.startswith("["):
json_string = "[" + json_string + "]"
if not "," in json_string:
json_string = re.sub(r'\s+', ' ', json_string)
json_string = json_string.replace(" ", ",")
if '"' in json_string or "'" in json_string:
json_string = re.sub(r'"', '', json_string)
json_string = re.sub(r"'", '', json_string)
json_data = json.loads(json_string)
byte_array = bytearray(json_data)
if convert_to == OutputType.UTF8:
print(byte_array.decode('utf-8'))
elif convert_to == OutputType.INT:
# Solana encoding is Little Endian
print(int.from_bytes(byte_array, 'little'))
else:
print('Unexpected error!', file=sys. stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment