Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a huge text file with digits representing an 8 bit value in binary. I want to convert these to hexadecimal (or decimal, doesn't really matter). That is, I have a text file containing e.g.

0 0 0 0  1 1 0 1
0 0 1 1  1 0 0 1
0 1 0 0  0 1 0 1
1 0 0 0  1 1 0 1

(just 8 bits) and I'd want to convert this to, say,


It sounds like this could be done with an awk script/vim macro, or a combination of any other tools.

share|improve this question
up vote 5 down vote accepted

Here a snippet of bash scripting to do that

while read line; do
    n=$((2#${line// /}))
    printf '0x%02X\n' "$n"
done <input-file

where 2# means base 2 and ${var// /} means "remove all spaces"

share|improve this answer

With Perl:

perl -ne 's/ *//g; printf("0x%02x\n", eval("0b$_"))' somefile.txt
share|improve this answer

With awk:

awk '{d=0; for (i=1; i<=NF; i++) {d=(d*2)+$i} printf "0x%02x\n", d}' binary.txt

Or with bc:

(echo obase=16; ibase=2; sed 's/ //g' binary.txt) | bc
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.