4

I have a HEX string in my bash script like the following:

1B6C00001AD615

I want to write this string in a binary file. (the binary representation of this string in a file that can be read with any normal hex editor for example)

I tried to use "bc" with ibase=16 and obase=2 , got the binary result in a string and tried to echo that to a file like in following example

echo -n -e 0100011000100101010101000010010

But when I try

vim -b myFile  

It does not appear as it should. Any suggestions>

Panos
  • 7,227
  • 13
  • 60
  • 95
  • 1
    See: [linux shell scripting: hex string to bytes](http://stackoverflow.com/q/1604765/3776858) – Cyrus Jun 03 '16 at 16:45

1 Answers1

2

You can always use bc for base conversions if you are interested in the binary representation of the value, e.g.

$ echo "obase=2; ibase=16; 1B6C00001AD615" | bc
11011011011000000000000000000000110101101011000010101

(note: your binary representation of the value in your question is incorrect)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • I had to do what you said + truncate the new lines and spaces that bc adds to split long values. Also I had to get that and echo it with "echo -e" to the file to make it work. I still have to verify if the output is exactly correct but I need to change some more stuff first. and YES :) my binary representation is incorrect for the reason why it was random and the representation of the HEX I wrote above. I just wanted to show what I want, not the actual result. – Panos Jun 06 '16 at 16:12
  • Sure, I understood what you wanted, no big deal on the binary in your question, I just wanted to make sure we were on the same page and if not, give you a chance to point it out. Glad it helped. Good luck with your scripting. – David C. Rankin Jun 06 '16 at 20:24