Technical Article

BIFF8 XLUnicodeString Decoding in Delphi: cch and fHigh

The eleven bytes 46 6F 72 65 63 61 73 74 20 51 33 spell Forecast Q3 in a BIFF8 trendline caption. Hand those same bytes to a UTF-16 reader and the caption turns into five CJK ideographs, U+6F46 U+6572 U+6163 U+7473 U+5120, with the trailing 33 dropped on the floor. The record was never damaged. The byte just before the text, fHigh, was 0, which means one byte per character, and the length field before it counted characters rather than bytes

Those two header fields, cch and fHigh, decide everything about how the rest of an XLUnicodeString is read: which decoder runs, how many bytes it may consume, and what code points come out. Get either one wrong and the result is a plausible-looking string of the wrong length or the wrong script

What cch and fHigh tell a BIFF8 reader

[MS-XLS] 2.5.293 defines XLUnicodeString as a length, a flag byte and the characters. The length, cch, is a character count. The low bit of the flag byte, fHighByte, says whether each character is stored as two bytes of UTF-16 or as one byte. In the one-byte form, which the spec calls compressed, every character has a high byte of zero that was simply left out, so byte $E9 stands for U+00E9 and byte $80 stands for U+0080. No code page is involved. That last point is the one most hand-written decoders miss, and it matters more than the byte count once a workbook contains anything outside ASCII

Excel picks the form per string. A sheet name, a trendline caption or a PivotTable view name whose characters all sit below U+0100 is usually written compressed; add one Greek or Chinese character and the whole string switches to UTF-16. So the same record type arrives in both shapes in ordinary files, and a reader that was only ever exercised against one shape will look correct right up to the first workbook that uses the other. Some record layouts also drop the length from the string itself and keep cch elsewhere in the record header (the NoCch variants), which moves the offsets around but leaves the rule the same: characters for the length, one flag for the width

GetWideString counts bytes, not characters

HotXLS reads raw record bodies through TXLSBlob, and every string reader on that class takes its Count argument in bytes. TXLSBlob.GetWideString(Index, Count) builds a WideString of Count div SizeOf(WideChar) characters, so a 16-bit payload needs cch * 2. Pass the character count straight from the header and you get the first cch div 2 characters back, with no exception, because the request stayed inside the record. The 8-bit reader for BIFF8 is TXLSBlob.GetCompressedUnicodeString(Index, Count), which takes cch bytes and turns each one into the matching code unit in U+0000 to U+00FF

// 16-bit payload (fHigh = 1): cch characters, cch * 2 bytes
Name := Data.GetWideString(Start, cch * 2);           // the whole text
Name := Data.GetWideString(Start, cch);               // first cch div 2 characters only

// 8-bit payload (fHigh = 0): cch characters, cch bytes
Name := Data.GetCompressedUnicodeString(Start, cch);  // byte $nn becomes U+00nn
Name := Data.GetWideStringWithZero(Start, cch);       // byte pairs glued into wrong code points
Name := WideString(Data.GetString(Start, cch));       // goes through the ANSI code page

On NUL, GetWideString and GetString cut the result at the first one, while the WithZero variants and GetCompressedUnicodeString keep embedded NULs. Asking for more than the record holds is the one mistake that does make noise: every TXLSBlob reader raises Blob read exceeds data size when Index + Count runs past the data. Under-reading has no such alarm

The reader semantics behind TXLSBlob string decoding in HotXLS: GetWideString runs SetString over a PWideChar with Count div SizeOf(WideChar) so a character count halves the text, GetWideStringWithZero marks NUL retention rather than width, and GetString plus GetStringWithZero are the one-byte counterparts returning AnsiString
Every reader counts its input in bytes, and only the WithZero suffix changes terminator behaviour, which is why passing a bare cch to a wide reader silently returns half the characters

The WithZero suffix trips people up because it sounds like a width switch. It marks NUL retention and nothing else. A very natural chain of reasoning goes: GetWideString wants cch * 2, so GetWideStringWithZero must be the variant that takes cch directly. It compiles, it returns a WideString, and it hands back half as many characters as the header promised, each one assembled from two neighbouring ASCII bytes. That is exactly the Forecast Q3 result from the opening paragraph

Why does a compressed string need its own reader?

Because casting an AnsiString to WideString runs the bytes through the ANSI code page of the machine doing the decoding, and the spec says compressed bytes are code units with the high byte removed. The two agree for plain ASCII. They part ways as soon as a byte is $80 or higher

  • On a Windows-1252 system the cast turns $80 into U+20AC (the euro sign), while the file means U+0080; bytes such as $81 and $8D have no 1252 mapping at all
  • On a system whose ANSI code page is 936, $E9 is the lead byte of a double-byte character, so café stored as 63 61 66 E9 turns its last character into a replacement character or drops it, depending on the conversion
  • The same workbook therefore decodes differently on two developer machines, which makes the bug look like a locale problem in the test environment rather than a decoding choice

The HotXLS decoders covered in this article (chart captions, PivotTable view links, cached formula strings, text box text) read their fHigh = 0 payloads with GetCompressedUnicodeString, so the result depends only on the bytes in the file. GetString still has a job: BIFF5 and older files have no flag byte, their strings really are code-page text governed by the CODEPAGE record, and that is the path where an AnsiString read followed by a code-page conversion is correct. The older formats are covered in more detail in reading Excel 2.0 through 4.0 files in Delphi. For BIFF8, a compressed string read through GetString is wrong even when every test passes, because every test machine happens to share one code page

How HotXLS decodes a BIFF8 string in Delphi by reading cch and the fHigh flag first: fHigh 1 dispatches to TXLSBlob.GetWideString with a cch * 2 byte count, fHigh 0 dispatches to the one-byte reader with plain cch, a wrong pairing returns an empty or half-length string without an error, and only a read past the end of the record raises
The flag and the length travel together: the encoding chosen in the header decides both which reader reads the characters and how many bytes that reader is allowed to consume

A four-byte check catches both the code-page mistake and the width mistake, and it runs without any workbook on disk. The Assert calls are checks to add in your own test project

var
  Blob: TXLSBlob;
  Name: WideString;
begin
  Blob := TXLSBlob.Create(16);
  try
    Blob.AddByte(4);                       // cch: four characters
    Blob.AddByte(0);                       // fHigh = 0: one byte per character
    Blob.AddByte($63); Blob.AddByte($61);  // c a
    Blob.AddByte($66); Blob.AddByte($E9);  // f, then U+00E9 with its high byte dropped

    Name := Blob.GetCompressedUnicodeString(2, Blob.GetByte(0));
    Assert(Name = 'caf' + WideChar($00E9));   // your own check
    Assert(Length(Name) = Blob.GetByte(0));   // your own check

    // For comparison only: this result changes with the ANSI code page
    Name := WideString(Blob.GetString(2, Blob.GetByte(0)));
  finally
    Blob.Free;
  end;
end;

SXViewLink and the per-encoding length gate

SXViewLink ($0858, [MS-XLS] 2.4.316) packs both asymmetries into one eight-byte header, which makes it the cleanest worked example. The layout is rt(2), unused(2), reserved(2), cch(1), fHigh(1), followed by the characters: cch * 2 bytes of UTF-16 when fHigh is 1, cch bytes when it is 0. cch tops out at 255 because the length field is a single byte. Excel writes the record into the chart globals ahead of Units, next to PivotChartBits ($0859, [MS-XLS] 2.4.196), whenever a chart sheet is bound to a PivotTable view; the record-level picture of that machinery is in writing BIFF8 PivotTable records in Delphi

The SXViewLink $0858 layout HotXLS gates per encoding: rt, unused and reserved words fill offsets 0 to 5, cch sits at 6 capped at 255, fHigh at 7 selects cch * 2 UTF-16 bytes or cch one-byte characters, and gating both branches behind 8 + cch * 2 would make Excel-written 8-bit PivotSourceName values decode as empty
SXViewLink packs both asymmetries into one record, and the guard has to be computed per encoding, because a wide-only length check rejects every 8-bit name Excel writes before any read happens

A defensive decoder checks DataLength before reading, so a truncated record yields no name instead of an exception. The trap is computing that check once. A gate written as 8 + cch * 2 for both branches looks conservative, yet a compressed body is only 8 + cch bytes long, so that gate rejects practically every 8-bit view name Excel writes, and the caller sees an empty PivotSourceName with no hint why. HotXLS gates each branch with its own arithmetic, and a hand-written handler for the same record should do the same

// Your own helper: SXViewLink body, [MS-XLS] 2.4.316
// rt(2) unused(2) reserved(2) cch(1) fHigh(1) characters...
function ReadViewLinkName(Data: TXLSBlob; out Name: WideString): Boolean;
var
  Cch: LongWord;
begin
  Result := False;
  Name := '';
  if Data.DataLength < 8 then Exit;
  Cch := Data.GetByte(6);
  if Cch = 0 then Exit;
  if (Data.GetByte(7) and $01) <> 0 then
  begin
    if Data.DataLength < 8 + Cch * 2 then Exit;   // wide gate
    Name := Data.GetWideString(8, Cch * 2);
  end
  else
  begin
    if Data.DataLength < 8 + Cch then Exit;       // narrow gate
    Name := Data.GetCompressedUnicodeString(8, Cch);
  end;
  Result := True;
end;

You rarely need to write that handler against HotXLS itself. TXLSCustomChart.GetChartModel returns a TXLSChartModel whose PivotSourceName and IsPivotChart fields come from exactly this record, and each TXLSChartTrendline on a series carries its caption in Name. The Trendline record ($2050, [MS-XLS] 2.4.328) is the second place the pairing shows up in chart decoding: 28 bytes of numeric payload, a two-byte cch at offset 28, fHigh at offset 30, characters from offset 31. That is where the Forecast Q3 bytes from the opening live

Strings that cross a Continue boundary

A BIFF record body is capped at 8,224 bytes, so long strings spill into Continue records ($003C), and two record families handle the spill in opposite ways. The String record ($0207, [MS-XLS] 2.4.268), which holds the cached text result of a formula, writes its flag byte once. The Continue segments that follow are raw character bytes with no flag of their own, and [MS-XLS] 2.5.293 guarantees that when fHighByte is 1 the break falls on a two-byte boundary. HotXLS reads the first segment from offset 3 (after cch and the flag) and each later segment from offset 0, computing a per-segment character count from the segment length and still passing bytes, segCh * 2, to GetWideString

Text boxes and cell comments stored through a TxO record do it differently: each Continue segment that carries text opens with its own flag byte, and the width can change from one segment to the next. A string can start compressed and finish in UTF-16. HotXLS re-reads the flag at offset 0 of every text segment and reads characters from offset 1. Carrying the first segment's width across the whole string works for every comment that happens to be pure ASCII, then produces garbage from the first segment boundary onward in the one that is not

When is GetBiffString the better call?

For a field that is a standard XLUnicodeString with its own length prefix, TXLSBlob.GetBiffString(var Index, is8bit, iswide) does the whole job: it reads the length, reads the flag byte, picks GetWideString with len * 2 or GetCompressedUnicodeString with len, and advances Index past the characters. The two Boolean parameters are easy to misread. is8bit describes the width of the length field (one byte instead of two), and iswide says whether a flag byte follows the length at all, which is true for BIFF8 and false for BIFF5 and older

var
  Offset: LongWord;
  Name: WideString;
begin
  Offset := 6;  // SXViewLink: the one-byte cch starts here, fHigh follows at 7
  // is8bit = True: the length field is one byte wide
  // iswide = True: a flag byte follows the length (BIFF8)
  Name := Data.GetBiffString(Offset, True, True);
  // Offset now points at the first byte after the characters
end;

With iswide set to False, GetBiffString reads the characters through GetString and casts, which is the right treatment for BIFF5 code-page text. Both branches stop at the first NUL; GetBiffStringWithZero is the variant that keeps embedded NULs

Pick by how much you trust the input. GetBiffString is shorter and gets the width logic right every time, but a record whose declared length runs past its body raises Blob read exceeds data size, and that exception travels up through whatever is decoding the record. The hand-rolled gate above costs a dozen more lines and turns the same truncated record into a missing name. For anything that walks third-party workbooks, the gate is the better default: a malformed SXViewLink should cost one view name, and the rest of the chart should still load. For records your own code wrote a moment ago, GetBiffString is fine, and an exception there points straight at a bug in the writer

If you maintain an XLS import path in Delphi or C++Builder and would rather not keep a BIFF8 string decoder of your own in sync with every record layout, the HotXLS Delphi spreadsheet component already applies these width and length rules across its XLS reader and writer, and it handles XLSX as well without Excel or OLE automation on the machine