L'implementazione (s) non funzionano per i caratteri non 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
Per superare questo è necessario serializzare i byte di la stringa che utilizza la codifica dei caratteri richiesta, che può essere multi-byte per carattere.
Ci sono alcuni "problemi" con questo.
- Ricordare che tutti i tipi numerici sono firmati nella JVM.
- Non c'è un byte senza segno.
In java idiomatico si utilizza il byte basso di un numero intero e lo si maschera in questo modo ovunque lo si utilizzi.
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 ha (unchecked-byte)
di fare effettivamente la stessa.
Ad esempio, utilizzando UTF-8 si può fare questo:
(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
Utilizzare una libreria Java? – Marcin
Lo hai già – Ankur
@Ankur: Apparentemente non come la risposta di sw1nn mostra: è per questo che vorrei una funzione esistente se possibile. –