【问题标题】:Byte collection to string on clojure字节收集到 clojure 上的字符串
【发布时间】:2017-12-01 02:56:52
【问题描述】:

以下代码

(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) 将 byte.array 转换为 String。
  • 是的,我一开始就是这么打算的。

标签: string clojure encryption


【解决方案1】:
(let [byte-array (caesar-block-cypher 1 "Hello, world!")]
    (apply str (map char byte-array)))

【讨论】:

  • 在一般情况下,java字节被签名:(apply str (map #(char (bit-and % 255)) byte-array))
【解决方案2】:

像这样使用java的String构造函数快速创建字符串,

(let [b (caesar-block-cypher 1 "Hello World")]
  (String. b))

【讨论】:

    【解决方案3】:

    您可以使用slurp,它也适用于字节数组:

    来自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)
    

    【讨论】:

      【解决方案4】:

      AFAIK 停止者芯片只是转移字符你为什么要处理字节,

      (let [s "Attack" k 1 encoded (map #(char (+ (int %) k)) s) decoded (map #(char (- (int %) k)) encoded)] (apply str decoded))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-20
        • 2016-03-28
        • 2021-03-27
        • 1970-01-01
        • 2021-12-08
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多