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.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

  1. import numpy as np
  2. ### Binary operations
  3. def hweight(n):
  4. c = 0
  5. while n>0:
  6. c += (n & 1)
  7. n >>= 1
  8. return c
  9. def hdistance(x,y):
  10. return hweight(x^y)
  11. def binary_writing(n, nb_bits=32, with_hamming=False):
  12. n = np.array(n)
  13. w, h = np.zeros((nb_bits, len(n))), np.zeros((len(n)))
  14. for ind in range(nb_bits):
  15. w[ind] = (n & 1)
  16. h += w[ind]
  17. n >>= 1
  18. ind += 1
  19. return (w, h) if with_hamming else w
  20. ### Conversion
  21. def to_hex(v, nb_bits=16):
  22. try:
  23. v_hex = v.hex()
  24. except AttributeError:
  25. v_hex = hex(v)[2:]
  26. return '0'*(nb_bits//4-len(v_hex)) + v_hex
  27. def split_octet(hexstr):
  28. return [hexstr[i:i+2] for i in range(0, len(hexstr), 2)]
  29. def to_signed_hex(v, nb_bits=16):
  30. try:
  31. return split_octet(to_hex(v & ((1<<nb_bits)-1), nb_bits=nb_bits))
  32. except TypeError as err:
  33. raise TypeError('Error to transform a <{}> into signed hex.'.format(type(v))) from err
  34. ### Write function
  35. def write(_input, uint, nb_bits=16):
  36. uint = to_signed_hex(uint, nb_bits=nb_bits)
  37. for i in range(nb_bits//8):
  38. _input.write(uint[i]+'\n')
  39. def write_list(_input, uint_list, nb_bits=16):
  40. for uint in uint_list:
  41. write(_input, uint, nb_bits=nb_bits)
  42. ### Print Utils
  43. class Color:
  44. HEADER = '\033[95m'
  45. OKBLUE = '\033[94m'
  46. OKCYAN = '\033[96m'
  47. OKGREEN = '\033[92m'
  48. WARNING = '\033[93m'
  49. FAIL = '\033[91m'
  50. ENDC = '\033[0m'
  51. BOLD = '\033[1m'
  52. UNDERLINE = '\033[4m'