Skip to content

Instantly share code, notes, and snippets.

@e3krisztian
Last active March 3, 2016 14:23
Show Gist options
  • Save e3krisztian/1e416ebe2de520e5e5b5 to your computer and use it in GitHub Desktop.
Save e3krisztian/1e416ebe2de520e5e5b5 to your computer and use it in GitHub Desktop.

Convert code from last class to functions

function: tohex1(n) n in {0..15}

assert tohex1(0) == '0'
assert tohex1(15) == 'F'

function: tohex2(n) n in {0..255}

assert tohex2(0) == '00'
assert tohex2(15) == '0F'
assert tohex2(255) == 'FF'

Lists, for loop

function tohex8(bytes):

# bytes = list of bytes
assert len(bytes) == 8

hexdump from list of 8 items: separated by a space character:

assert tohex8([0, 1, 2, 3, 121, 12, 13, 189]) == ' 00 01 02 03 79 0C 0D BD'

Character encoding

  • ascii (video)
    • ord(), chr()
  • hexdump ascii part

function toascii1(n) -> string of length 1 replace control characters (char code < 32) and "extended" characters (char code > 126) with '.'

assert toascii1(97) == 'a'
assert toascii1(98) == 'b'
assert toascii1(19) == '.'
assert toascii1(127) == '.'
assert toascii1(147) == '.'

function toascii(bytes) -> string representation of bytes:

assert toascii([0, 0x68, 0x65, 0x6C, 0x6F, 0x20, 0]) == '.hello..'

Improvement

assert len(bytes) <= 8
# but length of output remains the same!

assert tohex8([0, 1, 121, 12, 13, 189]) == ' 00 01 79 0C 0D BD      '

Slices

function: tohex16(bytes) hexdump from a list of 16 items: after first 8 add another space for visual separation

    assert tohex16(list(range(16))) == ' 00 01 02 03 04 05 06 07  08 09 0A 0B 0C 0D 0E 0F'

Dictionaries

function: make_name_id_map(names) names: list of names output: dictionary of name -> id

where id is the nth item in the list if duplicates are removed e.g.

assert make_name_id_map(['a', 'b', 'a', 'b', 'c', 'c']) == {'a': 0, 'b': 1, 'c': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment