# -*- coding: utf-8 -*- """ Created on Sun Nov 3 15:30:59 2019 This module converts string to hex, hex to string, ... @author: Patrice MEGRET """ import binascii def hex_to_string(h, show='y', coding='Latin-1'): """Conversion from hex to string. Args: h: hexa string show: print conversion (default 'y') coding: string coding (default 'Latin-1') Returns: h_s: string coded with coding Internal: h_by: h in byte """ h_by = binascii.unhexlify(h) h_s = h_by.decode(coding) if show == "y": print("Hex = ", h, "Len = ", len(h)) print("Bytes = ", h_by, "Len = ", len(h_by)) print('{0} = {1}, Len = {2!r}'.format(coding, h_s, len(h_s))) print('ASCII = {0!a}, Len = {1}'.format(h_s, len(h_s))) print("\n") return h_s def hex_to_byte(h, show='y', coding='Latin-1'): """Conversion from hex to byte. Args: h: hexa string show: print conversion (default 'y') coding: string coding (default 'Latin-1') Returns: h_by: h in byte """ h_by = binascii.unhexlify(h) if show == "y": print("Hex = ", h, "Len = ", len(h)) print("Bytes = ", h_by, "Len = ", len(h_by)) print("\n") return h_by def string_to_hex(s, show="y", coding="Latin-1"): """Conversion from string to hex. Args: s: string show: print conversion (default 'y') coding: string coding (default 'Latin-1') Returns: s_h: string in hexa Internal: s_by: s in byte with coding """ s_by = s.encode(coding) s_h = binascii.hexlify(s_by) if show == "y": print('ASCII = {0!a}, Len = {1}'.format(s, len(s))) print('{0} = {1}, Len = {2!r}'.format(coding, s, len(s))) print("Bytes = ", s_by, "Len = ", len(s_by)) print("Hex = ", s_h, "Len = ", len(s_h)) print("\n") return s_h def byte_to_hex(b, show="y", coding="Latin-1"): """Conversion from byte to hex. Args: b: bytes show: print conversion (default 'y') coding: string coding (default 'Latin-1') Returns: b_h: string in hexa """ b_h = binascii.hexlify(b) if show == "y": print("Bytes = ", b, "Len = ", len(b)) print("Hex = ", b_h, "Len = ", len(b_h)) print("\n") return b_h def hex_to_bin(h, show="y"): """Conversion from hex to bin. Args: h: hexa string show: print conversion (default 'y') Returns: b: binary equivalent of h """ b = bin(int(h, 16)) # b is a string beginning with 0b if show == "y": print("Bin = ", b, "Len = ", len(b) - 2) print('\n') return b def hex_to_bin_des(h, show="y"): """Conversion from hex to bin and display 64 bits. Args: h: hexa string show: print conversion (default 'y') Returns: b: binary equivalent of h """ b = bin(int(h, 16)) # b is a string beginning with 0b if show == "y": print('Bin = {0:064b}'.format(int(h, 16))) print('\n') return b def bin_to_hex(b, show="y"): """Conversion bin to hex. Args: b: binary string show: print conversion (default 'y') Returns: h: hexa equivalent of h """ h = hex(int(b, 2)) # h is a string beginning with 0x if show == "y": print("Hex = ", h, "Len = ", len(h) - 2) print('\n') return h def bin_to_hex_des(b, show="y"): """Conversion bin to hex and display 16 hexa. Args: b: binary string show: print conversion (default 'y') Returns: h: hexa equivalent of h """ h = hex(int(b, 2)) # h is a string beginning with 0x if show == "y": print('Hex = {:016x}'.format(int(b, 2))) print('\n') return h def xor_hex(h1_str, h2_str): """Xor between two hexa strings. Args: h1_str: hexa string 1 h2_str: hexa string 2 Returns: print xor between the two hexa strings """ i1 = int(h1_str, 16) i2 = int(h2_str, 16) x = i1 ^ i2 xb_str = bin(x) n1 = xb_str.count('1') print(xb_str, n1) print('\n') def binvalue(val, bitsize): """Return the binary value as a string of a given size. Args: val: integer or one character bitsize: number of bits for the conversion Returns: binval: string of bitsize-length """ # bin returns a string beginning with 0b ==> extract [2:] to cut these two characters binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:] if len(binval) > bitsize: raise "binary value larger than the expected size" while len(binval) < bitsize: binval = "0" + binval # Add as many 0 as needed to get the wanted size return binval def hexvalue(val, hexsize): """Return the hex value as a string of the given size. Args: val: integer or one character hexsize: number of hex for the conversion Returns: hexval: string of hexsize-length """ # hex returns a string beginning with 0x ==> extract [2:] to cut these two characters hexval = hex(val)[2:] if isinstance(val, int) else hex(ord(val))[2:] if len(hexval) > hexsize: raise "hex value larger than the expected size" while len(hexval) < hexsize: hexval = "0" + hexval # Add as many 0 as needed to get the wanted size return hexval def string_to_hex_array(text): """Convert a string into a list of hex. Args: text: string Returns: array: array of hexvalues """ array = list() for char in text: hexval = hexvalue(char, 2) # Get the char value on two hex array.extend([x for x in list(hexval)]) # Add the hex to the final list return array def hex_array_to_string(array): """Recreate the string from the hex array. Args: array: array of hex Returns: res: string """ res = ''.join([chr(int(y, 16)) for y in [''.join([str(x) for x in hexa]) for hexa in nsplit(array, 2)]]) return res def bit_array_to_hex(array, bitgroup, hexsize): """Return the hex value from an array of bits. Args: array: array of bits bitgroup: number of bits to be grpoupo for the conversion hexsize: number of hex for the conversion of bitgroup bits Returns: res: string of hex """ res = ''.join( [hexvalue(int(y, 2), hexsize) for y in [''.join([str(x) for x in hexa]) for hexa in nsplit(array, bitgroup)]]) return res def nsplit(s, n): # Split a list into sublists of size "n" return [s[k:k + n] for k in range(0, len(s), n)] if __name__ == '__main__': hs = b'370FFF' hex_to_string(hs) ss = 'test é' string_to_hex(ss) hex_to_bin('FF') bin_to_hex('1111') xor_hex('FF', '11')