你的實現(S)不用於非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中籤名。
- 沒有無符號字節。
在慣用的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
使用Java庫前導零? – Marcin 2012-04-08 13:02:30
你已經擁有它 – Ankur 2012-04-08 14:30:17
@Ankur:顯然不是sw1nn的答案顯示 - 這就是爲什麼我想要一個現有的功能,如果可能的話。 – 2012-04-15 18:30:54