Convert Binary Data to Hexadecimal in a Shell Script

Convert binary data to hexadecimal in a shell script

Perhaps use xxd:

% xxd -l 16 -p /dev/random
193f6c54814f0576bc27d51ab39081dc

Convert a decimal number to hexadecimal and binary in a shell script

The following one-liner should work:

printf "%s %08d 0x%02x\n" "$1" $(bc <<< "ibase=10;obase=2;$1") "$1"

Example output:

$ for i in {1..10}; do printf "%s %08d 0x%02x\n" "$i" $(bc <<< "ibase=10;obase=2;$i") "$i"; done
1 00000001 0x01
2 00000010 0x02
3 00000011 0x03
4 00000100 0x04
5 00000101 0x05
6 00000110 0x06
7 00000111 0x07
8 00001000 0x08
9 00001001 0x09
10 00001010 0x0a

Convert decimal to hexadecimal in UNIX shell script

echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc

How can i search for an hexadecimal content in a file in a linux/unix/bash script?

A first approach without any error handling could look like

#!/bin/bash

BINFILE=$1
SEARCHSTRING=$2

HEXSTRING=$(xxd -p ${BINFILE} | tr -d "\n")
echo "${HEXSTRING}"

echo "Searching ${SEARCHSTRING}"
OFFSET=$(grep -aob ${SEARCHSTRING} <<< ${HEXSTRING} | cut -d ":" -f 1)

echo ${OFFSET}:${BINFILE}

I've used xxd here because of Does hexdump respect the endianness of its system?. Please take also note that according How to find a position of a character using grep? grep will return multiple matches, not only the first one. The offset will be counted beginning from 1, not 0. To substract 1 from the variable ${OFFSET} you may use $((${OFFSET}-1)).

I.e. search for the "string" ELF (HEX 454c46) in a system binary will look like

./searchHEX.sh /bin/yes 454c46
7f454c460201010000000000000000000...01000000000000000000000000000000
Searching 454c46
2:/bin/yes

Convert int to hex in shell script

Use the %x format to the printf command to do the conversion, as in printf 0x%x num. To pass the converted value as argument to another command, use the $(...) executive quotes:

$ i=8
$ while [ $i -lt 16 ]; do
> echo $(printf 0x%x $i)
> i=$(expr $i + 1)
> done
0x8
0x9
0xa
0xb
0xc
0xd
0xe
0xf

Linux script to convert byte data into a hex string

Should you want only the hex strings:

$ echo '0Y0*†HÎ*†HÎ=B¬`9E>ÞÕ?ÐŽ·‹ñ6ì­Â‰&ÉÐL_cüsyxoú¢'|od -vt x1|awk '{$1="";print}'
30 59 30 2a e2 80 a0 48 c3 8e 2a e2 80 a0 48 c3
8e 3d 42 c2 ac 60 39 45 3e c3 9e c3 95 3f c3 90
c5 bd c2 b7 e2 80 b9 c3 b1 36 c3 ac c2 ad c3 82
e2 80 b0 26 c3 89 c3 90 4c 5f 63 c3 bc 73 79 78
6f c3 ba c2 a2 0a

You can avoid the awk part by just using od -vt x1 -A n. Thanks @Stefan van den Akker.



Related Topics



Leave a reply



Submit