[英]Byte collection to string on clojure
The following code 以下代码
(defn caesar-block-cypher
"Computes the caesar block cypher for the given text with the k key. Returns an array of bytes"
[k text]
(let [byte-string (.getBytes text)]
(loop [return-byte-array [] byte-string byte-string]
(if (= '() byte-string)
return-byte-array
(recur
(conj return-byte-array (byte (+ k (first byte-string))))
(rest byte-string))))))
Returns an array of bytes after processing the caesar cipher with key k at text. 在处理带有密钥k的caesar密码后,返回一个字节数组。 I want to convert back the byte array to a string or perform the cipher over the string directly, but
(new String return-byte-array)
doesn't work. 我想将字节数组转换回字符串或直接对字符串执行密码,但
(new String return-byte-array)
不起作用。 Any suggestions? 有什么建议?
EDIT: Thanks for the responses. 编辑:感谢您的回复。 I recodified this on a more functional style (that actually works):
我在一个更实用的风格(实际上有效)上重新编写了这个:
(defn caesar-block-cypher
"Computes the caesar block cypher for the given text with the k key."
[k text & more]
(let [byte-string (.getBytes (apply str text (map str more)))]
(apply str (map #(char (mod (+ (int %) k) 0x100)) byte-string))))
(let [byte-array (caesar-block-cypher 1 "Hello, world!")]
(apply str (map char byte-array)))
Use java's String constructor to create string quickly like this, 使用java的String构造函数快速创建字符串,
(let [b (caesar-block-cypher 1 "Hello World")]
(String. b))
AFAIK ceaser chipher just shifts chars why are you dealing with bytes, AFAIK ceaser chipher只是改变字符为什么你要处理字节,
(let [s "Attack"
k 1
encoded (map #(char (+ (int %) k)) s)
decoded (map #(char (- (int %) k)) encoded)]
(apply str decoded))
You can use slurp
, it also works for byte arrays: 你可以使用
slurp
,它也适用于字节数组:
From https://clojuredocs.org/clojure.core/slurp#example-588dd268e4b01f4add58fe33 来自https://clojuredocs.org/clojure.core/slurp#example-588dd268e4b01f4add58fe33
;; you can read bytes also
(def arr-bytes (into-array Byte/TYPE (range 128)))
(slurp arr-bytes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.