utility string functions

convert string into binary representation (8 bits per char)

split string into chars, for each char get ordinal number, and create string using 8bit  format of the number. Concat all

def str_2_binrep(s):
  return "".join(['{0:008b}'.format(ord(c)) for c in list(s)])


>>> str_2_binrep("Hello World")

If you want to have a space in between, just write

'{0:008b} '


split string into groups of n characters

fill array with substrings, range(start, stop, stepwidth)

def str_splitintogroups(s, n):
  return [s[i : (i+n) ] for i in range(0, len(s), n)]


>>> str_splitintogroups("split string into groups", 3)
['spl', 'it ', 'str', 'ing', ' in', 'to ', 'gro', 'ups']

XOR of two strings

zip builds tuples containing the ith char of each string; for each pair the xor of the octal number of the char is converted into char and appended

def str_xor(s1, s2):
  return "".join([chr( ord(c1) ^ ord(c2) ) for (c1,c2) in zip(s1, s2)])


>>> str_xor("Hello", "World")

>>> str_xor("Hello", "Hello")

Encode String as hex, and decode back

String encode, see http://docs.python.org/2/library/codecs.html#standard-encodings for possible encodings (python 2); output is using 2 digits each per byte of input


>>> "BibiBlocksberg".encode('hex')

>>> "BibiBlocksberg".encode('hex').decode('hex')

Dec to Hex, Hex to Dec

How to convert a decimal number into a hex representation:


>>> hex(1000)

>>> "%X"%1000

How to convert a from hex (or other) back to decimal representation:


>>> int("3E8", 16)

>>> int("1001", 2)

Comments are closed.