Advertisement
bash-masters

bin2inc.sh !! Slow, but effective!

Dec 31st, 2012
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.24 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. hash sed fold || {
  4.     printf "%s\n" "bin2inc: error: missing program dependencies";
  5.     exit 1; # if you don't have sed or fold, get them.
  6. } >&2;
  7.  
  8. [[ -n $2 ]] && {
  9.     [[ -f "$2" && -r "$2" ]] || {
  10.         printf "%s\n" "bin2inc: error: argument 2 is not a valid file: $2";
  11.         exit 2; # c'mon man file data must "exist"
  12.     } >&2;
  13. }
  14.  
  15. stream() {
  16.     local IFS='';
  17.     local -i bytes=0
  18.     while read -r -N1 r; do
  19.         printf "0x%02X, " "'$r"; let bytes++;  
  20.     done < "${1:-/dev/stdin}";
  21.     echo $bytes >&7;
  22. }
  23.  
  24. exec 7<> <(:);
  25. byteField="$( { stream < "$2"; echo -n 0x00; } | fold -sw 87 | sed  's/^/    /')";
  26. read -u 7 bytes; exec 7>&-;
  27.  
  28. (( bytes )) || {
  29.     echo $0: error: no content was provided;
  30.     echo $0: warning rubbish redirection files may be present;
  31.     exit 7;
  32. } >&2;
  33.  
  34. id=${1:-binary_data};
  35.  
  36. echo "/*
  37.  
  38. auto-generated file include
  39.  
  40. encoded by bin2inc.sh (C) 2012 Hypersoft bash-masters
  41.  
  42. git it here: https://github.com/hypersoft/bash-masters
  43.  
  44. date: `date`
  45. resource: ${2:-/dev/stdin}
  46. developer: $USER
  47.  
  48. content-identifier: ${id}
  49.  
  50. content-length-identifier: ${id}_length
  51. content-length: $bytes
  52.  
  53. zero-terminated: yes
  54. zero-padding: 1
  55.  
  56. */
  57.  
  58. unsigned char $id[] = {
  59.  
  60. $byteField
  61.  
  62. };
  63.  
  64. unsigned long int ${id}_length = ${bytes}L;
  65. "
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement