Skip to content

MultiFormatWriter: fix encoding binary std::string #599

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion core/src/MultiFormatWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,24 @@ MultiFormatWriter::encode(const std::wstring& contents, int width, int height) c
}
}

static std::wstring ToUInt8WideString(const std::string& s) {
std::wstring ws(s.begin(), s.end());
// Keep only the first byte of `wchar_t` and remove the sign bits
// from the `char` conversion. Without this, any `char` > 127 will
// be negative in `wchar_t`, too, which breaks later.
for (int i = 0, l = ws.length(); i < l; ++i) {
ws[i] &= 0xff;
}
return ws;
}

BitMatrix MultiFormatWriter::encode(const std::string& contents, int width, int height) const
{
return encode(FromUtf8(contents), width, height);
return encode(
_encoding == CharacterSet::BINARY
? ToUInt8WideString(contents)
: FromUtf8(contents),
width, height);
}

} // ZXing