To avoid code duplication, I extracted the hex-formatting code into a separate function. Please review.