Python-ELMO is a Python library which offers an encapsulation of the binary tool ELMO, in order to manipulate it easily in Python and SageMath script.
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

  1. import numpy as np
  2. ### Binary operations
  3. def hweight(n):
  4. """ Return the Hamming weight of 'n' """
  5. c = 0
  6. while n>0:
  7. c += (n & 1)
  8. n >>= 1
  9. return c
  10. def hdistance(x,y):
  11. """ Return the Hamming distance between 'x' and 'y' """
  12. return hweight(x^y)
  13. def binary_writing(n, nb_bits=32, with_hamming=False):
  14. """ Return the binary writing 'w' of 'n' with 'nb_bits'
  15. If with_hamming is True, return a couple (w, h) with 'h' the Hamming weight of 'n'
  16. """
  17. n = np.array(n)
  18. w, h = np.zeros((nb_bits, len(n))), np.zeros((len(n)))
  19. for ind in range(nb_bits):
  20. w[ind] = (n & 1)
  21. h += w[ind]
  22. n >>= 1
  23. ind += 1
  24. return (w, h) if with_hamming else w
  25. ### Conversion
  26. def to_hex(v, nb_bits=16):
  27. """ Convert the value 'v' into a hexadecimal string (without the prefix 0x)"""
  28. try:
  29. v_hex = v.hex()
  30. except AttributeError:
  31. v_hex = hex(v)[2:]
  32. return '0'*(nb_bits//4-len(v_hex)) + v_hex
  33. def split_octet(hexstr):
  34. """ Split a hexadecimal string (without the prefix 0x)
  35. into a list of bytes described with a 2-length hexadecimal string
  36. """
  37. return [hexstr[i:i+2] for i in range(0, len(hexstr), 2)]
  38. def to_signed_hex(v, nb_bits=16):
  39. """ Convert the signed value 'v'
  40. into a list of bytes described with a 2-length hexadecimal string
  41. """
  42. try:
  43. return split_octet(to_hex(v & ((1<<nb_bits)-1), nb_bits=nb_bits))
  44. except TypeError as err:
  45. raise TypeError('Error to transform a <{}> into signed hex.'.format(type(v))) from err
  46. ### Write function
  47. def write(_input, uint, nb_bits=16):
  48. """ Write in '_input' the value 'uint' by writing each byte
  49. with hexadecimal format in a new line
  50. """
  51. uint = to_signed_hex(uint, nb_bits=nb_bits)
  52. for i in range(nb_bits//8):
  53. _input.write(uint[i]+'\n')
  54. def write_list(_input, uint_list, nb_bits=16):
  55. """ Write in '_input' the list of values 'uint_list' by writing each byte
  56. with hexadecimal format in a new line
  57. """
  58. for uint in uint_list:
  59. write(_input, uint, nb_bits=nb_bits)
  60. ### Print Utils
  61. class Color:
  62. """ Color codes to print colored text in stdout """
  63. HEADER = '\033[95m'
  64. OKBLUE = '\033[94m'
  65. OKCYAN = '\033[96m'
  66. OKGREEN = '\033[92m'
  67. WARNING = '\033[93m'
  68. FAIL = '\033[91m'
  69. ENDC = '\033[0m'
  70. BOLD = '\033[1m'
  71. UNDERLINE = '\033[4m'