Clojure中如何将字节集转换为字符串

12
以下代码
(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))))))
返回经过凯撒密码使用密钥k加密处理后的字节数组。我想将字节数组转换回字符串,或者直接使用密文对字符串执行解密操作,但是 (new String return-byte-array) 不起作用。有什么建议吗?
(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))))

你返回的不是一个字节数组而是一个字符串。 (String.b) 将把一个字节数组转换为字符串。 - mac
是的,这正是我一开始的意图。 - Pedro Montoto García
4个回答

26
(let [byte-array (caesar-block-cypher 1 "Hello, world!")]
    (apply str (map char byte-array)))

8
通常情况下,Java字节是有符号的:(apply str (map #(char (bit-and % 255)) byte-array)) - Martin Carpenter

22
使用Java的字符串构造函数可以快速创建字符串,就像这样:
(let [b (caesar-block-cypher 1 "Hello World")]
  (String. b))

10

6
据我所知,凯撒密码只是简单地移位字符,为什么你要处理字节呢?

(让[s“攻击”
      k 1
      编码(map#(char(+(int%)k))s)
      解码(map#(char(-(int%)k))编码)]
  (应用str解码))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接