Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Created August 25, 2014 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpotlightKid/b6c1e90747636a47b2ce to your computer and use it in GitHub Desktop.
Save SpotlightKid/b6c1e90747636a47b2ce to your computer and use it in GitHub Desktop.
Convert a string in ASCII hexadecimal notation into a list of integers.
# -*- coding:utf-8 -*-
"""Convert a string in ASCII hexadecimal notation into a list of integers.
Example::
>>> convert_hexstring('F0 7E 7F 06 01 F7')
[240, 126, 127, 6, 1, 247]
>>> convert_hexstring('f07E7F 6 1 F7')
[240, 126, 127, 6, 1, 247]
You may use upper or lowercase letters for hexadecimal numbers and arbitrary
whitespace between bytes. When there is no whitespace between numbers, each
byte must have two hexadecimal digits, using a leading zero if necessary.
"""
__all__ = ('convert_hexstring',)
def convert_hexstring(s):
"""Return bytes from hexadecimal notation in s as a list of integers."""
result = []
for group in s.split():
for hex in (group[i:i+2] for i in range(0, len(group), 2)):
result.append(int(hex, 16))
return result
if __name__ == '__main__':
totest = (
('F0 7E 7F 06 01 F7', [240, 126, 127, 6, 1, 247]),
('F07E7F0601F7', [240, 126, 127, 6, 1, 247]),
('f07e7f0601f7', [240, 126, 127, 6, 1, 247]),
('f0 7e 7f 06 01 f7', [240, 126, 127, 6, 1, 247]),
('f0 7e 7f 6 1 f7', [240, 126, 127, 6, 1, 247]),
('f07E7f 6 1 F7', [240, 126, 127, 6, 1, 247])
)
for s, expected in totest:
assert convert_hexstring(s) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment