あなたの実装はASCII以外の文字では機能しません.
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(= "\u2195" (unhexify(hexify "\u2195")))
false ; should be true
これを克服するには、必要な文字エンコーディングを使用して文字列のバイトをシリアル化する必要があります。これは、文字ごとにマルチバイトにすることができます。
これにはいくつかの「問題」があります。
- JVM ではすべての数値型が符号付きであることに注意してください。
- unsigned-byte はありません。
慣用的なJavaでは、整数の下位バイトを使用し、使用した場所でこのようにマスクします。
int intValue = 0x80;
byte byteValue = (byte)(intValue & 0xff); -- use only low byte
System.out.println("int:\t" + intValue);
System.out.println("byte:\t" + byteValue);
-- output:
-- int: 128
-- byte: -128
clojure は(unchecked-byte)
同じことを効果的に行う必要があります。
たとえば、UTF-8 を使用すると、次のことができます。
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
; with the above implementation:
;=> (hexify "\u2195")
"e28695"
;=> (unhexify "e28695")
"↕"
;=> (= "\u2195" (unhexify (hexify "\u2195")))
true