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.

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.
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:
| name | category | remark |
|---|---|---|
| 北京市 | 首都 | 中文编码测试 |
| 上海市 | 直辖市 | 黄浦江 |
| 广州市 | 省会 | 珠江三角洲 |
| 成都市 | 省会 | 天府之国 |
The three variants differ only in the DBF encoding and the presence of a codepage file:
| Fixture | DBF encoding | .cpg | Files |
|---|---|---|---|
gbk-with-cpg | GBK | GBK | 5 (.cpg, .dbf, .prj, .shp, .shx) |
gbk-no-cpg | GBK | none | 4 (same set minus .cpg) |
utf8-control | UTF-8 | UTF-8 | 5 (.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.
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:
| Field | Value |
|---|---|
| Version byte | 0x03 (dBASE III) |
| Last update | 2026-07-20 |
| Number of records | 4 (uint32 LE at offset 4) |
| Header length | 129 bytes (uint16 LE at offset 8) |
| Record length | 241 bytes (uint16 LE at offset 10) |
| Language driver ID (offset 29) | 0x00 |
| Field descriptors | name C(80), category C(80), remark C(80) |
| Total file size | 1,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.

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.
Here is record 0's name field, trimmed of its trailing space padding:
| Fixture | Hex bytes | Length | Correct text |
|---|---|---|---|
gbk-with-cpg | b1 b1 be a9 ca d0 | 6 | 北京市 |
gbk-no-cpg | b1 b1 be a9 ca d0 | 6 | 北京市 |
utf8-control | e5 8c 97 e4 ba ac e5 b8 82 | 9 | 北京市 |

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.
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 | .cpg | utf-8 | gbk | gb18030 | big5 | latin-1 |
|---|---|---|---|---|---|---|
gbk-with-cpg | GBK | ERROR | OK / correct | OK / correct | OK / WRONG | OK / WRONG |
gbk-no-cpg | none | ERROR | OK / correct | OK / correct | OK / WRONG | OK / WRONG |
utf8-control | UTF-8 | OK / correct | ERROR | ERROR | ERROR | OK / 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

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.
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
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.
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.
| Encoding | Phrase | Encoded bytes | Stored | Decoded result |
|---|---|---|---|---|
| UTF-8 | 北京市 | 9 | fits | 北京市 |
| GBK | 北京市 | 6 | fits | 北京市 (4 bytes spare) |
| UTF-8 | 中文编码测试 | 18 | first 10 | unexpected end of data at byte 9 |
| GBK | 中文编码测试 | 12 | first 10 | 中文编码测 — silently loses one character |
| UTF-8 | 广州市天河区珠江新城 | 30 | first 10 | unexpected end of data at byte 9 |
| GBK | 广州市天河区珠江新城 | 20 | first 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

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.
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:
| Fixture | utf-8 score | gbk score | Verdict |
|---|---|---|---|
gbk-with-cpg | 0.000 | 1.000 | gbk |
gbk-no-cpg | 0.000 | 1.000 | gbk |
utf8-control | 1.000 | 0.889 | utf-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.

Figure 6. Trust .cpg, check LDID, score the bytes, decode, then verify a byte-for-byte round trip.
In production the chain should be:
.cpg first. If present and recognised, trust it. It is the producer's explicit statement.0x00 means "no hint", which is what our fixtures show.gb18030 rather than gbk for the actual decode so rare characters survive.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.
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.
"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.
.dbf, so geometry type does not change the analysis, but field widths do; the shipped fixtures use 80-byte fields, while the truncation experiment uses a constructed 10-byte field.undetermined by the threshold in section 8 — which is the correct conservative answer, since ASCII is valid in every candidate encoding.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 -> 北京市.
.cpg should be writtenA 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.