Skip to content

Instantly share code, notes, and snippets.

@mathgeniuszach
Created November 3, 2021 18:50
Show Gist options
  • Select an option

  • Save mathgeniuszach/3acdb4c21f8d3cd6ea5de04e15391bad to your computer and use it in GitHub Desktop.

Select an option

Save mathgeniuszach/3acdb4c21f8d3cd6ea5de04e15391bad to your computer and use it in GitHub Desktop.
Space efficient sbin2h. Only saves space in the header file, as compilation makes it all the same.
function(sbin2h header assetdir)
string(TOUPPER ${assetdir} hdef)
string(REGEX REPLACE "^[0-9]|[^A-Z0-9_]+" "_" hdef ${hdef})
file(WRITE ${header} "#ifndef BIN_${hdef}_H\n#define BIN_${hdef}_H\n\n")
file(GLOB_RECURSE assets "${assetdir}/*")
foreach(asset ${assets})
# Get variable name
string(REGEX MATCH "${assetdir}.*" fname ${asset})
string(REGEX REPLACE "${assetdir}[/\\\\]" "" fname ${fname})
string(REGEX REPLACE "^[0-9]|[^A-Za-z0-9_]+" "_" fname ${fname})
string(TOUPPER ${fname} fname)
# Read file
file(READ ${asset} data HEX)
# Convert all characters to hex representation (with double quote concatenation)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "\\\\x\\1\"\"" data ${data})
# Simplify printable characters
foreach(ord RANGE 32 126)
string(ASCII ${ord} out)
if(NOT (ord EQUAL 34 OR ord EQUAL 59 OR ord EQUAL 92)) # Exclude quote, semicolon, and backslash
string(HEX "${out}" hex)
string(REGEX REPLACE "\\\\x${hex}\"\"" "${out}" data ${data})
endif()
endforeach()
# Simplify common escape sequences
set(escs 0 a b t n v f r "\"" "\\\\")
set(vals 00 07 08 09 0a 0b 0c 0d 22 5c)
foreach(i RANGE 9)
list(GET escs ${i} esc)
list(GET vals ${i} val)
string(REGEX REPLACE "\\\\x${val}\"\"" "\\\\${esc}" data ${data})
endforeach()
# Remove unnecessary double quote concatenation
string(REGEX REPLACE "\"\"([^A-Fa-f0-9])" "\\1" data ${data})
# Simplify the semicolon
string(REGEX REPLACE "\\\\x3b(\"\")?" ";" data ${data})
# Append data to output file (with additional null byte added to the end)
file(APPEND ${header} "const unsigned char ${fname}[] = \"${data}\";\nconst unsigned long ${fname}_SIZE = sizeof(${fname}) - 1;\n")
endforeach()
file(APPEND ${header} "\n#endif\n")
endfunction()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment