Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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))))
like image 841
Pedro Montoto García Avatar asked Aug 24 '11 20:08

Pedro Montoto García


4 Answers

(let [byte-array (caesar-block-cypher 1 "Hello, world!")]
    (apply str (map char byte-array)))
like image 156
Mikita Belahlazau Avatar answered Nov 17 '22 00:11

Mikita Belahlazau


You can use slurp, it also works for byte arrays:

From 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)
like image 33
svelten Avatar answered Nov 16 '22 22:11

svelten


Use java's String constructor to create string quickly like this,

(let [b (caesar-block-cypher 1 "Hello World")]
  (String. b))
like image 25
Bo Chen Avatar answered Nov 16 '22 23:11

Bo Chen


AFAIK ceaser chipher just shifts chars why are you dealing with bytes,


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

like image 22
Hamza Yerlikaya Avatar answered Nov 16 '22 22:11

Hamza Yerlikaya