one-liner: change binary constants in C source file to hex
Posted on January 28th, 2020 by whinger. Filed under Uncategorized.
If you have an old C compiler that won’t work with binary constants like 0b10101010 you’ll end up with a fatal compile error:
invalid suffix “b10101010” on integer constant
One-liner:
grep -l '\b0b[01][01]' . -r | while read f; do perl -np -e 's/\b0b([01]+)/sprintf("0x%X\/*%s*\/", oct("0b$1"), $1)/eg' < $f > $f.new && mv $f.new $f; done
This replaces all binary values with hex equivalents, with the binary value in C comments after.
This will fail if you have binary values inside /* comments */; you can remove the comment value from the replacement string if you prefer:
grep -l '\b0b[01][01]' . -r | while read f; do perl -np -e 's/\b0b([01]+)/sprintf("0x%X", oct("0b$1"))/eg' < $f > $f.new && mv $f.new $f; done