Skip to content

Instantly share code, notes, and snippets.

@bsmt
Created January 1, 2014 06:18
Show Gist options
  • Save bsmt/8205609 to your computer and use it in GitHub Desktop.
Save bsmt/8205609 to your computer and use it in GitHub Desktop.
Dirty run script for xcode that allows NSData objects containing binary data (hex strings) to be declared using literal statements.
#!/usr/bin/env python
'''
The problem: Making NSData objects from byte strings is a pain.
To convert 0xb801000000c3 to NSData I have to make an escaped C string somehow,
which is either going to be annoying hardcoding or unnecessary categories.
Most basic foundation classes have literals (@1, @"string", etc.). Why not NSData?
This fixes that.
Simply do: NSData *data = @<b801000000c3>;
and preprocess your file with clank.py path/to/file.m
'''
import re
import sys
import os
import binascii
path = sys.argv[1]
path = os.path.expanduser(path)
code_file = open(path, "r+")
code = code_file.read()
data_literal_pattern = "@<[\\s\\da-fA-F]+>"
all_literals = re.findall(data_literal_pattern, code, re.IGNORECASE)
for literal in all_literals:
hex = re.search("[\s\da-fA-F]+", literal).group()
hex = binascii.unhexlify(hex)
hex = hex.encode("string_escape")
# subtracting one from length because this uses C strings (null terminated)
nsdata_call = '[NSData dataWithBytes:\"{0}\" length:sizeof("{0}") - 1]'.format(hex)
code = code.replace(literal, nsdata_call)
code_file.seek(0)
code_file.write(code)
code_file.truncate()
code_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment