Skip to content

Instantly share code, notes, and snippets.

@tmciver
Created December 10, 2011 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmciver/1456800 to your computer and use it in GitHub Desktop.
Save tmciver/1456800 to your computer and use it in GitHub Desktop.
(defn hexstr1
[bytes]
(loop [cnt 0
mybytes (seq bytes)
hexstr ""]
(if (seq mybytes)
(cond
(= (mod (inc cnt) 24) 0) (recur (inc cnt) mybytes (str hexstr "\n"))
(= (mod (inc cnt) 12) 0) (recur (inc cnt) mybytes (str hexstr " "))
(= (mod (inc cnt) 3) 0) (recur (inc cnt) mybytes (str hexstr " "))
:else (recur (inc cnt) (rest mybytes) (str hexstr (format "%02X" (first mybytes)))))
hexstr)))
;; running (println (hexstr1 (range 1 33))) gives:
;;
;; 0102 0304 0506 0708 090A 0B0C 0D0E 0F10
;; 1112 1314 1516 1718 191A 1B1C 1D1E 1F20
@kumarshantanu
Copy link

(defn hstr                                                                      
   [bytes]                                                                       
   (let [f #(format "%02X" %)                                                    
         h (map f bytes)                                                         
         s (interpose \space  (partition-all 2 h))    ; thanks TimMc for \space
         s2 (interpose \space  (partition-all 8 s))
         s3 (interpose \newline (partition-all 4 s2))]
     (apply str (flatten s3))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment