GEOO.APPGEOO.APP
Back to all posts
2026-11-0528 min readShapefileDBFGBKUTF-8Character Encoding

Shapefile Chinese Text: A GBK, UTF-8 and .cpg Experiment

Three real Shapefile fixtures, twelve records, five decoders. A byte-level look at DBF encoding, why a decoder that does not throw can be the most dangerous one, how fixed-width fields truncate multi-byte characters, and a detection chain that classified 12/12 records correctly.

Chinese text in a Shapefile arrives as mojibake more often than it arrives correctly. The usual advice — "set the encoding to UTF-8" — does not help when you are the receiver of a file somebody else made, and it does not explain why one file shows 北京市 while another shows ±±¾©ÊÐ or 鍖椾含甯. The Shapefile format itself does not store the answer in the place you would expect.

I build geoo.app, a set of browser-local GIS converters. While testing the encoding-repair path, I generated three Shapefile fixtures from one UTF-8 GeoJSON source and measured what actually happens when five different decoders read them. This article reports those measurements: the raw DBF bytes, a decode matrix, a fixed-width truncation experiment, and a detection chain that classified all twelve records correctly without reading a .cpg file. Every hex string, error message and verdict below was produced from the real fixture files, not constructed for illustration.

The same six bytes decoded five different ways

Figure 1. Six DBF bytes. One decoder throws, two produce the correct word, and two succeed with the wrong characters. The last group is the dangerous one.

1. The three fixtures

All three Shapefiles were generated with ogr2ogr from a single UTF-8 source, source/chinese_points.geojson. The source contains four point features with Chinese values in three attributes:

namecategoryremark
北京市首都中文编码测试
上海市直辖市黄浦江
广州市省会珠江三角洲
成都市省会天府之国

The three variants differ only in the DBF encoding and the presence of a codepage file:

FixtureDBF encoding.cpgFiles
gbk-with-cpgGBKGBK5 (.cpg, .dbf, .prj, .shp, .shx)
gbk-no-cpgGBKnone4 (same set minus .cpg)
utf8-controlUTF-8UTF-85 (.cpg, .dbf, .prj, .shp, .shx)

The regeneration commands are the ones a GIS developer would actually use:

ogr2ogr -f "ESRI Shapefile" gbk-with-cpg/chinese_points_gbk.shp \
  source/chinese_points.geojson -lco ENCODING=GBK
ogr2ogr -f "ESRI Shapefile" gbk-no-cpg/chinese_points_gbk_no_cpg.shp \
  source/chinese_points.geojson -lco ENCODING=GBK
rm gbk-no-cpg/chinese_points_gbk_no_cpg.cpg
ogr2ogr -f "ESRI Shapefile" utf8-control/chinese_points_utf8.shp \
  source/chinese_points.geojson -lco ENCODING=UTF-8

Note what ENCODING=GBK does: it changes the bytes written into the DBF, and it writes a .cpg sidecar. It does not put anything into the DBF header that identifies GBK. That detail is the root of the whole problem, and the next section shows it directly.

2. What is actually inside the DBF

A dBASE III DBF file is a fixed-layout binary structure. Parsing the header of any of the three fixtures gives exactly the same result:

FieldValue
Version byte0x03 (dBASE III)
Last update2026-07-20
Number of records4 (uint32 LE at offset 4)
Header length129 bytes (uint16 LE at offset 8)
Record length241 bytes (uint16 LE at offset 10)
Language driver ID (offset 29)0x00
Field descriptorsname C(80), category C(80), remark C(80)
Total file size1,094 bytes

The raw first 32 bytes are:

03 7e 07 14 04 00 00 00 81 00 f1 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

0x81 is 129 and 0xf1 is 241. The arithmetic closes cleanly: 32 header bytes + 3 × 32 descriptor bytes + 1 terminator = 129, and 1 deletion flag + 3 × 80 character bytes = 241, so 129 + 4 × 241 + 1 EOF marker = 1,094.

Layout of the measured DBF file

Figure 2. Byte offsets of the measured fixture. The record area dominates, and the header carries no encoding hint.

The important finding is LDID = 0x00. The dBASE specification reserves header byte 29 for a language driver ID — a code that could identify the file's codepage — and a well-formed producer could use it to announce the encoding. All three fixtures leave it at zero. This is common in real Shapefiles, because GDAL writes the codepage to .cpg instead. So when the .cpg is missing, the DBF contains no encoding metadata whatsoever: no BOM (this is a binary, fixed-width format, not a text file), no declared charset, no self-describing marker. Only six bytes that could mean almost anything.

That is why the second fixture exists. It is byte-for-byte identical in its DBF to gbk-with-cpg, but nobody tells the reader how to decode it.

3. The bytes themselves

Here is record 0's name field, trimmed of its trailing space padding:

FixtureHex bytesLengthCorrect text
gbk-with-cpgb1 b1 be a9 ca d06北京市
gbk-no-cpgb1 b1 be a9 ca d06北京市
utf8-controle5 8c 97 e4 ba ac e5 b8 829北京市

The same word as two byte sequences

Figure 3. GBK uses two bytes per Chinese character; UTF-8 uses three. The control fixture stores 9 bytes for a three-character word.

GBK encodes 北 as b1 b1, 京 as be a9, 市 as ca d0. UTF-8 encodes the same three characters as e5 8c 97, e4 ba ac, e5 b8 82. Both sequences are valid byte strings. Neither carries a marker. The only difference a parser can observe is the pattern: UTF-8 Chinese sits in the E0–EF lead-byte range followed by two 80–BF continuation bytes, while GBK Chinese uses a 81–FE lead byte and a 40–FE trail byte. Section 8 turns that observation into a detector.

It also explains a second, quieter failure mode: a fixed-width DBF field that comfortably holds five Chinese characters in GBK (10 bytes) holds only three in UTF-8 (9 bytes). Section 7 measures what happens at the boundary.

4. Five decoders against three fixtures

I decoded record 0's name field with five codecs under strict error handling. All four records in each fixture behave identically, so the table shows the verdict once per fixture rather than four times:

Fixture.cpgutf-8gbkgb18030big5latin-1
gbk-with-cpgGBKERROROK / correctOK / correctOK / WRONGOK / WRONG
gbk-no-cpgnoneERROROK / correctOK / correctOK / WRONGOK / WRONG
utf8-controlUTF-8OK / correctERRORERRORERROROK / WRONG

The concrete strings, for the GBK fixture:

utf-8    -> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0
gbk      -> 北京市
gb18030  -> 北京市
big5     -> 控儔庈
latin-1  -> ±±¾©ÊÐ

And for the UTF-8 control:

utf-8    -> 北京市
gbk      -> UnicodeDecodeError
gb18030  -> UnicodeDecodeError
big5     -> UnicodeDecodeError
latin-1  -> å\x8c\x97京å¸\x82

Decode matrix for the three fixtures

Figure 4. Only the matching codec is correct. Big5 and latin-1 never raise, so "no exception" is not evidence of correctness.

Three conclusions are worth stating plainly.

A thrown error is good news. UnicodeDecodeError tells you the codec was wrong and gives you a byte offset. It is cheap to catch and cheap to recover from by trying the next candidate.

A successful decode is not evidence of anything. latin-1 maps all 256 byte values, so it can never fail. big5 happens to accept the GBK byte pairs and returns three perfectly valid — and perfectly wrong — Chinese characters. If your repair pipeline picks the first decoder that does not throw, it will pick big5 or latin-1 and silently corrupt the attributes. This is the single most common way encoding repair makes a file worse.

GB18030 is a superset of GBK. It decodes the GBK fixture correctly and is the safer fallback when the source might contain rare characters, but it still cannot decode the UTF-8 fixture. It is a better GBK, not a universal decoder.

There is a related trap: once text has become mojibake, decoding it again with another codec does not fix it. latin-1 followed by gbk produces a longer, more convincing-looking string of wrong characters. The repair must always go back to the original bytes and decode them once with the right codec.

5. A minimal DBF reader

The whole experiment rests on reading the DBF correctly, so here is the parser used above. It needs no third-party packages:

import struct
from pathlib import Path

def read_dbf(path: Path):
    b = path.read_bytes()
    n_records = struct.unpack_from('<I', b, 4)[0]
    header_len = struct.unpack_from('<H', b, 8)[0]
    record_len = struct.unpack_from('<H', b, 10)[0]
    ldid = b[29]

    fields, off = [], 32
    while off < header_len and b[off] != 0x0D:
        name = b[off:off + 11].split(b'\x00')[0].decode('ascii')
        fields.append({
            'name': name,
            'type': chr(b[off + 11]),
            'length': b[off + 16],          # field width in BYTES
        })
        off += 32

    records = []
    for i in range(n_records):
        rec = b[header_len + i * record_len:
                header_len + (i + 1) * record_len]
        pos, cells = 1, {}                  # byte 0 = deletion flag (' ' or '*')
        for f in fields:
            raw = rec[pos:pos + f['length']]
            cells[f['name']] = raw.rstrip(b'\x00').rstrip(b' ')
            pos += f['length']
        records.append(cells)

    return {'ldid': ldid, 'fields': fields, 'records': records}

Two details matter. rstrip(b'\x00').rstrip(b' ') removes padding without touching significant bytes; and the field length is a byte count, not a character count. On the UTF-8 fixture, an 80-byte field holds at most 26 Chinese characters, while on the GBK fixture it holds 40. Any code that treats field width as characters will truncate on one and not the other.

The .cpg check is trivial but should come first:

def declared_encoding(shp: Path) -> str | None:
    cpg = shp.with_suffix('.cpg')
    return cpg.read_text('ascii').strip() if cpg.exists() else None

6. Why you cannot brute-force your way out

A tempting strategy is "try every codec, keep the one that does not throw". Section 4 already shows why that fails: latin-1 never throws and big5 often does not. A slightly smarter version scores the result by counting Chinese characters — but 控儔庈 and 北京市 are both three Chinese characters, and both look plausible to a naive filter. Frequency analysis over a common-character dictionary can separate them, but that requires a dictionary, adds a dependency, and still fails on names, transliterations and rare place names.

The reliable signal is not in the decoded string. It is in the bytes before decoding.

7. Fixed-width fields cut multi-byte characters

I constructed a 10-byte character field — narrower than the shipped fixtures' 80-byte fields — and encoded four phrases into it, padding with spaces as DBF does. This is a constructed experiment rather than a measurement of the shipped files, and it is labelled as such in the figure.

EncodingPhraseEncoded bytesStoredDecoded result
UTF-8北京市9fits北京市
GBK北京市6fits北京市 (4 bytes spare)
UTF-8中文编码测试18first 10unexpected end of data at byte 9
GBK中文编码测试12first 10中文编码测 — silently loses one character
UTF-8广州市天河区珠江新城30first 10unexpected end of data at byte 9
GBK广州市天河区珠江新城20first 10广州市天河 — silently loses the rest
def store_dbf_field(text: str, width: int, encoding: str) -> bytes:
    encoded = text.encode(encoding)
    return encoded[:width].ljust(width, b' ')

def restore(raw: bytes, encoding: str) -> str:
    return raw.rstrip(b' ').decode(encoding)   # strict: incomplete UTF-8 raises

Truncation in a 10-byte DBF field

Figure 5. Ten byte slots. UTF-8 truncation can leave a half-character and raise on decode; GBK truncation is more likely to land on a character boundary and lose text silently.

The asymmetry is the interesting part. Cutting UTF-8 at byte 10 leaves the first byte of a three-byte sequence, so strict decoding fails loudly with unexpected end of data at byte 9. Cutting GBK at byte 10 lands exactly on a two-byte boundary and returns five perfectly valid characters — the sixth is simply gone, with no error at all. The GBK case is more dangerous, because nothing tells the user that a place name was shortened.

This is also why "just convert it to UTF-8" can lose data: exporting a GBK Shapefile whose fields were already truncated cannot restore the missing characters. The repair has to happen before any width is enforced.

8. A detection chain that works

The byte patterns from section 3 give a deterministic detector. It scores how much of the field conforms to a UTF-8 three-byte CJK sequence versus a GBK two-byte sequence, then picks the higher score:

def utf8_score(raw: bytes) -> float:
    b = raw.rstrip(b'\x00').rstrip(b' ')
    good, i = 0, 0
    while i < len(b):
        if (0xE0 <= b[i] <= 0xEF and i + 2 < len(b)
                and 0x80 <= b[i+1] <= 0xBF and 0x80 <= b[i+2] <= 0xBF):
            good += 3; i += 3
        elif b[i] < 0x80:
            good += 1; i += 1
        else:
            i += 1
    return good / len(b) if b else 0.0

def gbk_score(raw: bytes) -> float:
    b = raw.rstrip(b'\x00').rstrip(b' ')
    good, i = 0, 0
    while i < len(b):
        if (0x81 <= b[i] <= 0xFE and i + 1 < len(b)
                and 0x40 <= b[i+1] <= 0xFE and b[i+1] != 0x7F):
            good += 2; i += 2
        elif b[i] < 0x80:
            good += 1; i += 1
        else:
            i += 1
    return good / len(b) if b else 0.0

def detect(raw: bytes) -> str:
    u, g = utf8_score(raw), gbk_score(raw)
    if u >= 0.9 and u > g: return 'utf-8'
    if g >= 0.9 and g > u: return 'gbk'
    return 'undetermined'

Measured scores on record 0:

Fixtureutf-8 scoregbk scoreVerdict
gbk-with-cpg0.0001.000gbk
gbk-no-cpg0.0001.000gbk
utf8-control1.0000.889utf-8

All 12 records across the three fixtures were classified correctly, without reading any .cpg file. The third row is the instructive one: the UTF-8 byte sequence also scores 0.889 under the GBK pattern, because UTF-8 lead and continuation bytes largely fall inside GBK's valid ranges. A detector that asks "does this look like GBK?" would answer yes for both. Only comparing the two scores — or trying strict UTF-8 first — separates them.

The decision chain used for encoding repair

Figure 6. Trust .cpg, check LDID, score the bytes, decode, then verify a byte-for-byte round trip.

In production the chain should be:

  1. Read .cpg first. If present and recognised, trust it. It is the producer's explicit statement.
  2. Check LDID at header byte 29. Non-zero values can override or confirm; 0x00 means "no hint", which is what our fixtures show.
  3. Try strict UTF-8. A clean decode is strong evidence, because GBK Chinese almost never forms valid UTF-8.
  4. Otherwise score the byte patterns and pick the higher one; use gb18030 rather than gbk for the actual decode so rare characters survive.
  5. Verify by round trip. Decode, re-encode with the chosen codec, and compare to the original bytes. If they differ, the guess was wrong.
  6. Expose the guess to the user. Automatic detection should be an overridable default, not an unquestionable verdict. Real-world data includes mixed encodings within one DBF.

Step 5 is not redundant with step 4. A byte pattern can be ambiguous while still round-tripping — big5 decoding of the GBK fixture is reversible and wrong — so round-trip verification proves internal consistency, not semantic correctness. The pattern score is what selects between codecs; the round trip is what catches a mis-sliced field or a corrupted byte.

9. Repairing the file, and checking it worked

Once the encoding is known, the repair is a single decode per field followed by a clean UTF-8 export:

def repair_to_geojson(dbf_path: Path, encoding: str):
    dbf = read_dbf(dbf_path)
    features = []
    for cells in dbf['records']:
        props = {k: v.decode(encoding) for k, v in cells.items()}
        features.append({'type': 'Feature', 'properties': props,
                         'geometry': None})
    return {'type': 'FeatureCollection', 'features': features}

Applying repair_to_geojson(..., 'gbk') to the GBK fixture produced attribute sets that compare equal to the original UTF-8 source for all four records — 北京市 / 首都 / 中文编码测试, 上海市 / 直辖市 / 黄浦江, and so on. That equality check is the only meaningful proof that the repair worked; "the text looks Chinese now" is not.

When writing a Shapefile back out, write a UTF-8 .cpg:

from pathlib import Path
Path('clean.cpg').write_text('UTF-8', encoding='ascii')

In a browser, the same chain uses TextDecoder with fatal: true so an invalid sequence throws rather than substituting U+FFFD:

function decodeField(raw: Uint8Array, encoding: string): string {
  return new TextDecoder(encoding, { fatal: true }).decode(raw);
}

function strictUtf8(raw: Uint8Array): string | null {
  try {
    return new TextDecoder('utf-8', { fatal: true }).decode(raw);
  } catch {
    return null;                       // try gb18030 next
  }
}

// A Shapefile arrives as a set of sibling files; the user may select them together.
function findSidecar(files: FileList, suffix: string): File | undefined {
  return Array.from(files).find(f => f.name.toLowerCase().endsWith(suffix));
}

TextDecoder supports gbk and gb18030 in modern browsers through the Encoding Standard, but support for the exact label and for fatal-mode behaviour should be feature-detected. A RangeError from an unsupported label is not a decode failure and must not be mistaken for one. Also note that a Shapefile is a set of files — .shp, .shx, .dbf, .prj, .cpg — so the UI needs all of them; receiving only the .shp cannot produce attributes at all.

10. Common mistakes, and what the measurements say about each

"Just set QGIS to UTF-8." That changes how your application reads the bytes; it does not change the bytes. If the file is GBK, forcing UTF-8 produces the UnicodeDecodeError in the matrix.

"Use CP936, it is the same as GBK." CP936 is Microsoft's implementation of GBK with a small set of extra mappings. For the fixtures here they are equivalent; for rare characters and the euro sign they are not. gb18030 is the safer superset and is what I would use for the repair decode.

"Add a BOM." A DBF is a binary fixed-width record structure. A UTF-8 BOM at the start of a field becomes three stray bytes inside the first attribute; at the start of the file it corrupts the header. BOMs belong to text files, not DBFs.

"Decode the mojibake again to fix it." As noted in section 4, second-pass decoding increases entropy. Go back to the original bytes.

"Renaming .cpg fixes it." The sidecar is metadata for readers. Renaming or editing it changes how future readers interpret the same bytes — which is exactly what we want for a GBK file with a wrong .cpg — but it does not convert anything, and it cannot recover characters already lost to truncation.

"The DBF header has a codepage field, so just read it." It has one (LDID, byte 29), and in all three fixtures it is 0x00. Do not build a pipeline that assumes it is populated.

11. Limitations

12. Reproduce it

The fixtures are real files in the project's test data; comparable samples are on the sample data page. To see the core result in a few lines:

python3 - <<'PY'
from pathlib import Path
root = Path('testdata/vector-repair')
for d in ('gbk-with-cpg', 'gbk-no-cpg', 'utf8-control'):
    dbf = next((root / d).glob('*.dbf'))
    b = dbf.read_bytes()
    hdr, reclen = int.from_bytes(b[8:10], 'little'), int.from_bytes(b[10:12], 'little')
    raw = b[hdr + 1: hdr + 1 + 80].rstrip(b' ')   # first record, `name`
    print(d, 'ldid=', hex(b[29]), 'cpg=',
          (root / d / dbf.with_suffix('.cpg').name).read_text().strip()
          if (root / d / dbf.with_suffix('.cpg').name).exists() else None,
          'hex=', raw.hex(' '))
    for enc in ('utf-8', 'gbk', 'gb18030', 'big5', 'latin-1'):
        try:
            print('   ', enc, '->', raw.decode(enc))
        except UnicodeDecodeError as e:
            print('   ', enc, '-> ERROR', str(e)[:52])
PY

The first block should print ldid= 0x0 and cpg= None for gbk-no-cpg, followed by utf-8 -> ERROR and gbk -> 北京市.

13. Where to go next

A short FAQ:

Is .cpg part of the Shapefile standard? No. It is a de facto convention popularised by ESRI and GDAL, which is precisely why it is so often missing. The formal specification offers LDID in the DBF header, and producers frequently leave it at zero.

Why does my file show 鍖椾含甯 instead of ±±¾©ÊÐ? Those are the two classic mojibake shapes. 鍖椾含甯 is UTF-8 bytes read as GBK; ±±¾©ÊÐ is GBK bytes read as a single-byte Western encoding. Neither is recoverable by another decode — get the original bytes.

Should a converter auto-detect or ask? Ask, with a confident default. The detector in section 8 is deterministic on these fixtures, but the cost of a wrong guess is silent data corruption, which is worse than one extra click for the user.

The whole problem fits in one sentence: a DBF stores bytes, the meaning lives in a sidecar that may not exist, and the most dangerous decoder is the one that never complains.