47

Can anyone recommend a straightforward way/tool to convert hex to base64?

I'm using Linux and OS X.

Hello71
  • 8,397
  • 5
  • 40
  • 44
Tom Duckering
  • 603
  • 1
  • 5
  • 7

3 Answers3

78

Use xxd with the -r argument (and possibly the -p argument) to convert from hex to plain binary/octets and base64 to convert the binary/octet form to base64.

For a file:

cat file.dat | xxd -r -p | base64

For a string of hex numbers:

echo "6F0AD0BFEE7D4B478AFED096E03CD80A" | xxd -r -p | base64
Jess Bowers
  • 162
  • 6
Breton
  • 931
  • 7
  • 3
  • To prove that this is correct, you can perform the reverse operation and verify that the output of the reverse operation matches the input you provided to the above command. Eg. `echo -n $UUID | sed 's/-//g' | xxd -r -p | base64 | base64 --decode | xxd -u | cut -d ' ' -f 2-9 | sed 's/ //g'` – Gurjeet Singh May 01 '20 at 00:01
  • 1
    The important info here is the "-n" option of echo (don't exist on all plateform) which avoids the newline. – Sandburg Oct 15 '20 at 13:51
  • It produces base64 split by newlines. Use `base64 -w 0` instead of `base64` to avoid this. – Finesse Jul 28 '23 at 14:57
3

Well, it depends on the exact formatting of your data. But you can do it with a simple shell scripts:

 echo "obase=10; ibase=16; `cat in.dat`" | bc | base64 > out.dat

Modify as needed depending on your data.

pehrs
  • 371
  • 2
  • 10
  • 4
    That will convert the string of decimal digits. It's not clear if this is what the OP wants or if he has hex digits and wants the bytes they represent converted to base64. – Dennis Williamson Jun 29 '10 at 14:21
0

Well, if your hex data is the hex view of a file, just attach the file to a outlook or thunderbird message and then save the message to somewhere. Then open the file with a text editor and see B64 code :)

It functions on Windows, but I think it is a universal way since saving as .EML the attachment is encoded to B64.

kokbira
  • 5,307
  • 12
  • 42
  • 74