shell script to convert big endian to little endian

170 Views Asked by At

how can I convert big endian to little endian. I need to convert data from a file.

example data:

000000000000200200DC082DED2DEDED051F4032400454036A9891D53C370101EA0A

output:

0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000

thanks Ketan

found this script on the forum but it only does one at a time:

#!/bin/bash

# check 1st arg or stdin
if [ $# -ne 1 ]; then
if [ -t 0 ]; then
  exit
else
v=`cat /dev/stdin`
fi
else
v=$1
fi

i=${#v}

while [ $i -gt 0 ]
do
i=$[$i-2]
echo -n ${v:$i:2}
done

echo

5

There are 5 best solutions below

6
k314159 On BEST ANSWER

To read a file containing hex digits and reverse it using bytes, where each byte is represented by two hex digits:

#/bin/bash
while read -r line
do
  tac -rs .. <<< "$line"
done

Save it as e.g. rev.sh, chmod +x rev.sh, and run: rev.sh < myfile

0
Ed Morton On

Using any awk:

$ awk '{for (i=length($0)-1; i>0; i-=2) printf "%s", substr($0,i,2); print ""}' file
0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000

or using GNU awk for FPAT:

$ awk -v FPAT='..' '{for (i=NF; i>=1; i--) printf "%s", $i; print ""}' file
0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000

Alternatively, using rev to reverse the whole line and any sed to swap the characters in every pair:

$ rev file | sed 's/\(.\)\(.\)/\2\1/g'
0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000
$ sed 's/\(.\)\(.\)/\2\1/g' file | rev
0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000
0
dawg On

It seems what you want is:

  1. Reverse the string;
  2. Rereverse each pair of two hex digits.

If so:

s='000000000000200200DC082DED2DEDED051F4032400454036A9891D53C370101EA0A'

ruby -lne 'puts $_.reverse.scan(/../).map(&:reverse).join' <<< "$s"

Or with rev and sed:

echo "$s" | rev | sed -E 's/(.)(.)/\2\1/g'

Either prints:

0AEA0101373CD591986A0354044032401F05EDED2DED2D08DC000220000000000000
0
jhnc On
perl -nlE 'say reverse unpack "(A2)*"' file
  • for each line of file:
    • split into array of two-character strings
    • reverse the array
    • print it

May not produce desired output if line contains an odd number of characters.

5
user1934428 On

From man dd:

swab Swap every pair of input bytes.
If an input buffer has an odd number of bytes, the last byte will be ignored during swapping.

Therefore,

dd conv=swab example_data_file output_data_file

should do the job.