Last active
January 3, 2016 20:59
-
-
Save ffoxin/8518547 to your computer and use it in GitHub Desktop.
Replace binary numbers (ex. 0b00110101) with its hex representation (ex. 0x35). Useful for adopting arduino Sketch project sources for common IDE.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from os import listdir | |
from os.path import isfile, join | |
import re | |
def bin2hex(dir_path, extensions): | |
bin_match = re.compile('0b[01]{8}') | |
for file_name in listdir(dir_path): | |
file_path = join(dir_path, file_name) | |
if isfile(file_path): | |
if not extensions or any(file_name.endswith(ext) for ext in extensions): | |
with open(file_path) as source_file: | |
source = source_file.read() | |
source, replace_count = bin_match.subn(lambda bin_num: '0x%02X' % int(bin_num.group(), 2), source) | |
if replace_count: | |
with open(file_path, 'w') as source_file: | |
source_file.write(source) | |
print('%s: %u occurrence(s) were replaced' % (file_name, replace_count)) | |
if __name__ == '__main__': | |
path = 'd:\projects\embedded\led_key\TM1638' | |
exts = ['.h', '.cpp'] | |
bin2hex(path, exts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment