Click here to Skip to main content
13,146,014 members (46,336 online)
Click here to Skip to main content
Add your own
alternative version


Posted 4 Oct 2012

XOR Hex Strings in Linux Shell Script

, 4 Oct 2012
Rate this:
Please Sign up or sign in to vote.
Small shell script function to XOR hex strings


This is a simple shell script to XOR hex strings. I used it to generate sha1 hashes of files and XOR ing their hashes to create master result.

The Code

function  xor()
      local res=(`echo "$1" | sed "s/../0x& /g"`)
      shift 1
      while [[ "$1" ]]; do
            local one=(`echo "$1" | sed "s/../0x& /g"`)
            local count1=${#res[@]}
            if [ $count1 -lt ${#one[@]} ]
            for (( i = 0; i < $count1; i++ ))
                  res[$i]=$((${one[$i]:-0} ^ ${res[$i]:-0}))
            shift 1
      printf "%02x" "${res[@]}"

Sample Run

xor af36a125944af4682a239f2a5e35f5f91c671abe 249fecfe9fbfb5920f19e198944c788f5d7c64c9



Now let's see what this function does.

  1. Convert the first argument to an array of hex bytes by adding space and 0x after every two characters
  2. Loop through each argument
  3. Convert argument to array of hex values
  4. Get the maximum number of arguments between two arrays
  5. Loop through each array element and XOR values and store in result
  6. In the end, print hex values

Nice and simple now. This program can be used to XOR hash values of several files to generate a master result, i.e., XORed hashes.

Points of Interest

I've mostly worked on Windows environment, so this is my first hands on shell script in Linux. This also shows how to use loops, conditions, arrays.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
India India
I have been involved in C, C++ development for over a six year now. I have worked on projects involving games, insurance application, stats and reporting applications. Being busy with work I hardly got time to post my own articles but now I am getting more involved. I don't promise much but hopefully you'll see some more interesting articles from me in near future.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 4 Oct 2012
Article Copyright 2012 by Sanjay1982
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid