_byteordercodes.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. ''' Byteorder utilities for system - numpy byteorder encoding
  2. Converts a variety of string codes for little endian, big endian,
  3. native byte order and swapped byte order to explicit NumPy endian
  4. codes - one of '<' (little endian) or '>' (big endian)
  5. '''
  6. import sys
  7. __all__ = [
  8. 'aliases', 'native_code', 'swapped_code',
  9. 'sys_is_le', 'to_numpy_code'
  10. ]
  11. sys_is_le = sys.byteorder == 'little'
  12. native_code = sys_is_le and '<' or '>'
  13. swapped_code = sys_is_le and '>' or '<'
  14. aliases = {'little': ('little', '<', 'l', 'le'),
  15. 'big': ('big', '>', 'b', 'be'),
  16. 'native': ('native', '='),
  17. 'swapped': ('swapped', 'S')}
  18. def to_numpy_code(code):
  19. """
  20. Convert various order codings to NumPy format.
  21. Parameters
  22. ----------
  23. code : str
  24. The code to convert. It is converted to lower case before parsing.
  25. Legal values are:
  26. 'little', 'big', 'l', 'b', 'le', 'be', '<', '>', 'native', '=',
  27. 'swapped', 's'.
  28. Returns
  29. -------
  30. out_code : {'<', '>'}
  31. Here '<' is the numpy dtype code for little endian,
  32. and '>' is the code for big endian.
  33. Examples
  34. --------
  35. >>> import sys
  36. >>> from scipy.io.matlab._byteordercodes import to_numpy_code
  37. >>> sys_is_le = (sys.byteorder == 'little')
  38. >>> sys_is_le
  39. True
  40. >>> to_numpy_code('big')
  41. '>'
  42. >>> to_numpy_code('little')
  43. '<'
  44. >>> nc = to_numpy_code('native')
  45. >>> nc == '<' if sys_is_le else nc == '>'
  46. True
  47. >>> sc = to_numpy_code('swapped')
  48. >>> sc == '>' if sys_is_le else sc == '<'
  49. True
  50. """
  51. code = code.lower()
  52. if code is None:
  53. return native_code
  54. if code in aliases['little']:
  55. return '<'
  56. elif code in aliases['big']:
  57. return '>'
  58. elif code in aliases['native']:
  59. return native_code
  60. elif code in aliases['swapped']:
  61. return swapped_code
  62. else:
  63. raise ValueError(
  64. f'We cannot handle byte order {code}')