title: Translate encoding of string
body: <p>I have a string that is in Windows-1252 encoding, but needs to be converted to UTF-8.</p>
  
  <p>This is for a program that fixes a UTF-8 file that has fields containing Russian text encoded in <a href="https://en.wikipedia.org/wiki/Quoted-printable" rel="nofollow">quoted-printable</a> Windows-1252. Here's the code that decodes the <a href="https://en.wikipedia.org/wiki/Quoted-printable" rel="nofollow">quoted-printable</a>:</p>
  
  <pre><code>(defn reencode
      [line]
      (str/replace line #"=([0-9A-Fa-f]{2})=([0-9A-Fa-f]{2})"
          (fn [match] (apply str
              (map #(char (Integer/parseInt % 16)) (drop 1 match))))))
  </code></pre>
  
  <h3>Here's the final code:</h3>
  
  <pre><code>(defn reencode
      [line]
      (str/replace line #"(=([0-9A-Fa-f]{2}))+"
          (fn [[match ignore]]
              (String.
                  (byte-array (map
                      #(Integer/parseInt (apply str (drop 1 %)) 16)
                      (partition 3 match)))
                  "Windows-1252"))))
  </code></pre>
  
  <p>It fixes the encoding using <code>(String. ... "Encoding")</code> on all consecutive runs of quoted-printable-encoded characters. The original function was trying to decode pairs, so it would skip things like <code>=3D</code>, which is the quoted-printable entity for <code>=</code>.</p>