diff --git a/cpp/poppler-private.cpp b/cpp/poppler-private.cpp
index 4de2256..4f9808a 100644
--- a/cpp/poppler-private.cpp
+++ b/cpp/poppler-private.cpp
@@ -23,6 +23,7 @@
 #include "poppler-private.h"
 
 #include "GooString.h"
+#include "PDFDocEncoding.h"
 #include "Page.h"
 
 #include <ctime>
@@ -58,16 +59,16 @@ rectf detail::pdfrectangle_to_rectf(const PDFRectangle &pdfrect)
 
 ustring detail::unicode_GooString_to_ustring(const GooString *str)
 {
-    const char *data = str->getCString();
     const int len = str->getLength();
+    const char *data = str->getCString();
+    const char *data_end = data + len;
 
-    int i = 0;
     bool is_unicode = false;
     if ((data[0] & 0xff) == 0xfe && (len > 1 && (data[1] & 0xff) == 0xff)) {
         is_unicode = true;
-        i = 2;
+        data += 2; // skip BOM
     }
-    ustring::size_type ret_len = len - i;
+    ustring::size_type ret_len = len;
     if (is_unicode) {
         ret_len >>= 1;
     }
@@ -75,15 +76,15 @@ ustring detail::unicode_GooString_to_ustring(const GooString *str)
     size_t ret_index = 0;
     ustring::value_type u;
     if (is_unicode) {
-        while (i < len) {
-            u = ((data[i] & 0xff) << 8) | (data[i + 1] & 0xff);
-            i += 2;
+        while (data < data_end) {
+            u = ((*data & 0xff) << 8) | (*(data + 1) & 0xff);
+            data += 2;
             ret[ret_index++] = u;
         }
     } else {
-        while (i < len) {
-            u = data[i] & 0xff;
-            ++i;
+        while (data < data_end) {
+            u = pdfDocEncoding[ *data & 0xff ];
+            data ++;
             ret[ret_index++] = u;
         }
     }
