Python String/bytes as big number and back (last update: 2017-10-22, created: 2017-10-22) back to the list ↑
Example code I've written as part of an answer of a question about RSA on one of the Polish programming forums. Please note it was meant as a general example, and not as RSA OpenSSL compatible method that is safe/well written in any way.

The *_hack methods are actually what I use on CTFs/etc when I need to implement this fast (i.e. implementation time has to be short, runtime doesn't matter). The methods without this suffix are more what you would expect.

Please also note that I'm using Python's built-in bignum implementation. In (almost) any other language this would require either a library or a custom bignum implementation.

def str2num(s):
  s = bytearray(s)  # So I don't have to call ord() all the time.
  n = 0
  for v in s:
    n *= 0x100
    n += v
  return n

def num2str(n):
  o = []
  while n != 0:
    o.append(chr(n % 0x100))  # n & 0xff would work too
    n /= 0x100 # n >>= 8 would work too
  return ''.join(o)[::-1]


def str2num_hack(s):
  return int(s.encode("hex"), 16)

def num2str_hack(n):
  return hex(n).replace("L", "")[2:].decode("hex")


text = "Hello World"

enc_test1 = str2num(text)
dec_test1 = num2str(enc_test1)

enc_test2 = str2num_hack(text)
dec_test2 = num2str_hack(enc_test2)

print "Text:", text

print "Method 1 (encode):", enc_test1
print "Method 1 (decode):", dec_test1

print "Method 2 (encode):", enc_test2
print "Method 2 (decode):", dec_test2

Output:

Text: Hello World
Method 1 (encode): 87521618088882533792115812
Method 1 (decode): Hello World
Method 2 (encode): 87521618088882533792115812
Method 2 (decode): Hello World

【 design & art by Xa / Gynvael Coldwind 】 【 logo font (birdman regular) by utopiafonts / Dale Harris 】