Can a replacement character found in a utf8 text? I want to sanitize a malformed text and use a decoder that returns a replacement character on error. I would replace all "bad" bytes with '_'.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Short answer
Yes. U+FFFD (�) is an ordinary, perfectly valid Unicode code point whose UTF-8 byte sequence is EF BF BD.
Any program, author, or protocol can insert that character deliberately, so a “clean” UTF-8 file can legally contain it.
Once you have already decoded the byte stream you can no longer tell whether each � came from
• a genuine U+FFFD that was present in the source data, or
• an error that the decoder substituted with U+FFFD.
Therefore, searching the decoded text for � and treating it as “bad bytes” is unreliable.
What to do instead
Let the decoder put in the character you really want.
Most Unicode libraries let you supply a custom error-handler/callback:
Python example:
python
import codecs
def underscore(exc): # exc is a UnicodeDecodeError
if isinstance(exc, UnicodeDecodeError):
# Replace every offending byte with one '_'
return ('_' * (exc.end - exc.start), exc.end)
raise exc # re-raise for other kinds of errors
codecs.register_error('under', underscore)
clean_text = raw_bytes.decode('utf-8', errors='under')
If your decoding library cannot do that, decode with “replace”, but only if you are 100 % certain that real U+FFFD will never appear in your data. Otherwise you risk corrupting legitimate text.
Take-away
• U+FFFD can definitely appear in valid UTF-8.
• After decoding, you cannot know which � are “real” and which came from errors.
• Ask the decoder to use “_” (or whatever you prefer) as the replacement in the first place, or use a custom error callback so you never need to hunt for � afterwards.
User
I can check if the original byte sequence was EF BF BD and if it was i can simply skip it.
Assistant
You certainly can walk over the original byte stream and decide case-by-case what to do, but “just look for EF BF BD and drop it” is not enough to separate “real” U+FFFD characters from decoder-inserted ones.
Why?
Because every time you see the 3-byte sequence
code
EF BF BD # 0xEF 0xBF 0xBD
you have no context that tells you
The sender encoded an actual U+FFFD (perfectly legal), or
The sender produced some different invalid byte sequence, and your decoder already converted that to EF BF BD when it failed (i.e. you are no longer looking at the “original” bytes).
If you really do still have the raw bytes, you can avoid the ambiguity by never letting a decoder change the input in the first place. Do the scan yourself:
Algorithm (one pass)
Read one byte.
If it starts a valid UTF-8 sequence of length 1–4 and the continuation
bytes are valid → copy the entire sequence to output.
Otherwise → copy one underscore (or whatever you like) and advance by
one byte.
Repeat until the buffer is empty.
That way you never create an EF BF BD yourself, so if EF BF BD appears
in the input you know it was deliberate and you keep it unchanged.
Python reference implementation
python
def sanitize_utf8(data: bytes, replacement: str = '_') -> str:
out_chars = []
i = 0
n = len(data)
repl = replacement.encode('utf-8') # assumes ASCII replacement
while i < n:
b0 = data[i]
# 1-byte (ASCII) ----------------------------------------------
if b0 < 0x80:
out_chars.append(chr(b0))
i += 1
continue
# determine expected length from first byte
if 0xC2 <= b0 <= 0xDF: need = 2
elif 0xE0 <= b0 <= 0xEF: need = 3
elif 0xF0 <= b0 <= 0xF4: need = 4
else:
# illegal leading byte
out_chars.append(replacement)
i += 1
continue
# enough bytes left?
if i + need > n:
out_chars.append(replacement)
break
# check continuation bytes 0b10xxxxxx
cont = data[i+1 : i+need]
if any((c & 0xC0) != 0x80 for c in cont):
out_chars.append(replacement)
i += 1 # *only* skip the bad first byte
continue
# overlong / surrogate / >U+10FFFF checks can go here if wanted
try:
out_chars.append(bytes(data[i : i+need]).decode('utf-8'))
i += need
except UnicodeDecodeError: # catches overlong, surrogate, etc.
out_chars.append(replacement)
i += 1
return ''.join(out_chars)
User
I will do the sanitizing in place.
Assistant
Below is a straight-forward “in-place” recipe that turns every byte that starts an invalid UTF-8 sequence into the ASCII underscore 0x5F ('_').
Because you only overwrite bytes—never insert or delete—no reallocation or memmove is necessary, so you really are working in place.
Key ideas
• Walk through the buffer with an index i.
• When you meet a legal 1-, 2-, 3- or 4-byte sequence, just skip over it.
• Otherwise overwrite the single offending byte with 0x5F and advance by 1.
• After the pass you can decode with a strict UTF-8 decoder; it will never raise because the stream is now guaranteed to be well-formed (underscores are plain ASCII).
Reference implementation (C-like pseudocode)
c
void sanitize_utf8_in_place(unsigned char *p, size_t len)
{
size_t i = 0;
while (i < len) {
unsigned char b0 = p[i];
/* 1-byte (ASCII) ------------------------------------------------- */
if (b0 < 0x80) { i++; continue; }
/* 2-byte lead byte C2..DF --------------------------------------- */
if ((0xC2 <= b0 && b0 <= 0xDF) && i + 1 < len) {
unsigned char b1 = p[i+1];
if ((b1 & 0xC0) == 0x80) { i += 2; continue; }
}
/* 3-byte --------------------------------------------------------- */
else if ((0xE0 <= b0 && b0 <= 0xEF) && i + 2 < len) {
unsigned char b1 = p[i+1], b2 = p[i+2];
/* Check continuation bytes */
if ((b1 & 0xC0) == 0x80 && (b2 & 0xC0) == 0x80)
{
/* Over-longs, surrogates, etc. */
if ((b0 == 0xE0 && b1 < 0xA0) || /* overlong */
(b0 == 0xED && b1 >= 0xA0)) /* surrogate */
{
/* fall through → mark as invalid */
} else {
i += 3; continue;
}
}
}
/* 4-byte --------------------------------------------------------- */
else if ((0xF0 <= b0 && b0 <= 0xF4) && i + 3 < len) {
unsigned char b1 = p[i+1], b2 = p[i+2], b3 = p[i+3];
if ((b1 & 0xC0) == 0x80 && (b2 & 0xC0) == 0x80 && (b3 & 0xC0) == 0x80)
{
if ((b0 == 0xF0 && b1 < 0x90) || /* overlong */
(b0 == 0xF4 && b1 > 0x8F)) /* > U+10FFFF */
{
/* fall through */
} else {
i += 4; continue;
}
}
}
/* If we arrive here the *leading* byte was illegal ---------------- */
p[i] = 0x5F; /* '_' */
i++; /* Try again from the next byte */
}
}
User
I want to use a decoder that returns U+FFFD on error and advances the pointer into the buffer. I don't want to change the string's size.
Assistant
Yes, that can be done, provided that you still have the original bytes while you decode.
The idea is:
Feed the decoder one sequence at a time.
Let it tell you how many source-bytes it just consumed.
If it returned U+FFFD and those consumed bytes were not the legal UTF-8
sequence EF BF BD, treat the whole chunk as “bad” and overwrite every one
of those bytes with 0x5F (‘_’).
Otherwise leave the bytes untouched.
Repeat until the end of the buffer.
Because you only overwrite existing bytes—never insert or remove—you keep the
buffer length unchanged.
Reference implementation with ICU’s U8_NEXT
c
#include <unicode/utf8.h> /* ICU */
#include <stddef.h>
#include <stdint.h>
void sanitize_utf8_in_place(uint8_t *buf, size_t len)
{
size_t i = 0; /* current offset */
while (i < len)
{
size_t start = i; /* remember where this sequence begins */
UChar32 cp = 0;
/* ---- decode one code point (U+FFFD on error) ---- */
U8_NEXT(buf, i, len, cp); /* advances i past the sequence */
size_t consumed = i - start; /* number of bytes just eaten */
/* ---- was it an error? ----------------------------------------- */
bool bad = (cp == 0xFFFD) &&
!(consumed == 3 &&
buf[start] == 0xEF && buf[start+1] == 0xBF &&
buf[start+2] == 0xBD); /* EF BF BD is *legit* U+FFFD */
if (bad) {
for (size_t k = 0; k < consumed; ++k)
buf[start + k] = 0x5F; /* overwrite with '_' */
}
}
}
What happens?
• Valid sequences (ASCII, BMP, 4-byte planes and the real U+FFFD
) survive untouched.
• Any malformed sequence—over-longs, lone continuation bytes, truncated tails,
surrogate ranges, code points > U+10FFFF, …—turns into the
of underscores, so the total length is preserved.
User
The signature of the decoding function is: std::uint32_t decode_utf8_char(unsigned char const* &pos, unsigned char const* const end)
Assistant
Great—decode_utf8_char already gives you everything you need:
It advances pos past the bytes it just consumed (valid or not).
It delivers U+FFFD (0xFFFD) when it encountered an error.
So during the walk you only have to
remember where the sequence started,
call the decoder,
measure how many bytes were consumed (consumed = pos-start),
if the result was U+FFFD and the bytes were not the literal EF BF BD,
overwrite those consumed bytes with _ (0x5F).
Because you overwrite in place, the buffer length never changes.
• EF BF BD is just another legal 3-byte sequence.
• Once a decoder has run with errors='replace', the distinction between
“real” and “inserted” U+FFFD is lost.
• Therefore, if you need 100 % certainty, validate the raw bytes yourself,
replacing each invalid byte (or sequence) with “_” before you ever
decode.
If your language/runtime already offers a “replace with X” callback (Python’s codecs.register_error, Rust’s from_utf8_lossy_with, Java’s CodingErrorAction.REPLACE, iconv’s --unicode-subst=…), use that instead: let it output “_” on the fly and you’re done.
What the code does
• Valid sequences are left untouched (including the real UTF-8 for U+FFFD = EF BF BD if it was already in the file).
• Any illegal leading byte becomes an underscore.
• Orphaned continuation bytes (80..BF that don’t belong to a leader) are caught because they do not satisfy any of the “if” branches and thus fall into the final “invalid” case.
After the pass
c
/* strict decode will now succeed */
std::string clean = std::string((char*)p, len); // if you know it’s valid UTF-8
If you prefer “one underscore per whole bad sequence”
you will need an extra inner loop to skip continuation bytes and then perform a memmove to close the gap—no longer purely in place. Most people accept “one underscore per bad byte” because it is vastly simpler and keeps the byte count unchanged.
Language variants
• In Python replace the loop body with bytearray manipulation; logic is identical.
• In Rust change &mut [u8] in place.
• In Java or Go you typically copy into a new buffer instead; the same checks apply.
Why this works for your original goal
You never emit EF BF BD yourself, so if those three bytes are still present after sanitizing you know they represented a deliberate U+FFFD.
You can freely choose another replacement byte (e.g. ?) by changing 0x5F.
Happy sanitizing!
EF BF BD
same number
After this pass the entire buffer is guaranteed to be legal UTF-8,
so you can decode it later with a strict routine if desired.
If you cannot (or don’t want to) use ICU
The exact same strategy works with almost every API that
returns U+FFFD on error, and
tells you how many bytes it consumed.
Examples:
• C11 mbrtoc32 + MB_ERR_INVALID (glibc ≥ 2.28).
• C++20 std::mbrtoc32.
• Go utf8.DecodeRune.
• Rust std::str::from_utf8 inside a loop with manual slicing.
• .NET System.Text.UTF8Encoding with DecoderFallbackException off and
GetCharCount(...)/GetChars(...) to know the exact advance.
The only thing you must add is the same special-case check:
code
“Was the input exactly EF BF BD?
If yes, it is a *real* U+FFFD → leave it alone.”
Why you cannot do it after decoding
Once the bytes are gone you cannot tell whether a U+FFFD in the decoded
string came from the source or from the decoder.
Doing the replacement while you still see the raw bytes avoids that problem
and satisfies your “don’t change the string’s size” requirement at the same
time.
Usage:
cpp
std::string s = ...; // raw, possibly malformed UTF-8
sanitize_in_place(reinterpret_cast<unsigned char*>(s.data()),
reinterpret_cast<unsigned char*>(s.data() + s.size()));
// `s` now contains only valid UTF-8, length unchanged, bad bytes => '_'
Why the EF BF BD special-case?
EF BF BD is the valid UTF-8 for “real” U+FFFD.
If those three bytes were already in the input, we must not treat them as
damage.
Any other situation that produces U+FFFD (over-longs, broken continuation
bytes, truncated sequences, surrogate code points, > U+10FFFF, …) is truly an
error and gets replaced.
After the pass
The buffer is now guaranteed well-formed UTF-8, so you can decode it later
with a strict routine (or just keep using the same decoder without
worrying about failures).
That satisfies all three of your requirements:
• use the existing decoder,
• keep the buffer size,
• turn every malformed sequence into underscores. 👍