in reply to Illegal hexadecimal digit error

Note that you start getting this warning on the second trip through the loop. The first time through, $num gets a newline tacked onto the end of it. Remove the \n in the second sprintf, and the problem goes away.