Skip to content

Instantly share code, notes, and snippets.

@ffoxin
Last active January 3, 2016 20:59
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 ffoxin/8518547 to your computer and use it in GitHub Desktop.
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.
#!/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