LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   writing binary data via the shell? (https://www.linuxquestions.org/questions/programming-9/writing-binary-data-via-the-shell-421530/)

zero79 03-04-2006 08:21 AM

writing binary data via the shell?
 
Hello,

I was wondering if there was any way to write raw binary data to a file? Say I want a file to contain the hex data 1f332d01, is there a way to do something like

Code:

$ echo 1f332d01 | hex2binary > file
$ hexdump file
0000000 1f33 2d01

where hex2binary is some tool (I don't know if something like it exists or not) that takes hex data on standard input and outputs binary data on standard output. Any tool that would allow me to accomplish the goal of putting the above data into a file would be very useful to me.

I found that someone has written C code to do essentially this (http://www.engr.umd.edu/~yavuz/softw...ex2Binary.htm), but I'd prefer not to have to bring in someone else's code especially since there is no license information. Also, I would like to use an existing shell tool if it exists, otherwise, I will just write a short python script.

Anyway, thanks for any thoughts.

Mike

acid_kewpie 03-04-2006 08:48 AM

i'm not used to using hex really, but you can easily convert bases using bc:
Code:

echo "ibase=16; obase=2; 1F332D01" | bc
That'll give you your binary string, but if i use hexdump to read that when redirected, i don't get the original string back as fasr as i can tell.

bigearsbilly 03-04-2006 09:04 AM

look at perl's 'pack' function maybe

jlliagre 03-04-2006 11:35 AM

No need to use perl, a shell script can do it:
Code:

  while read w
  do
    for byte in $(echo $w | sed 's/../& /g')
    do
      printf "\\$(printf "%o" 0x$byte)"
    done
  done



All times are GMT -5. The time now is 09:52 PM.