我从一个服务中接收到一个字符串,该字符串显然使用 UTF-32 编码对其 unicode 字符进行编码,例如:\U0001B000
(C 风格的 unicode 编码)。但是,为了在 JSON 中序列化此信息,我必须将其编码为 UTF-16,例如:\uD82C\uDC00
。
但是,我不知道如何在 Java/Clojure 中读取这样的编码字符串,以及如何使用其他编码格式生成输出。
最佳答案
您可以使用以下方法从服务中读取接收到的字节:
(slurp received-bytes :encoding "UTF-32")
并使用以下方法写一个字符串:
(spit destination string-to-encode :encoding "UTF-16")
如果你的意思是你有一个表示编码字符二进制的字符串,那么你可以使用以下方法转换它:
(defn utf32->str [utf32-str]
(let [buf (java.nio.ByteBuffer/allocate 4)]
(.putInt buf (Integer/parseInt (subs utf32-str 2) 16))
(String. (.array buf) "UTF-32")))
(utf32->str "\\U0001B000" )
然后使用以下方法将其转换为 UTF-16:
(defn str->utf16 [s]
(let [byte->str #(format "%02x" %)]
(apply str
(drop 1 (map #(str "\\U" (byte->str (first %) ) (byte->str (second %) ))
(partition 2 (.getBytes s "UTF-16")))))))
这是一个示例运行:
(str->utf16 (utf32->str "\\U0001B000"))
;=> "\\Ud82c\\Udc00"
关于java - 在 Java/Clojure 中将 UTF-32 编码的字符串(C 样式)转换为 UTF-16(JSON 样式)编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027024/