Skip to content

Commit f3994b1

Browse files
committed
toAscii: replace logic with masking loop
Avoids having to deal with endianness. Signed-off-by: Rosen Penev <[email protected]>
1 parent a67c192 commit f3994b1

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

src/bmffimage.cpp

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,16 @@ BmffImage::BmffImage(BasicIo::UniquePtr io, bool /* create */, size_t max_box_de
8787
} // BmffImage::BmffImage
8888

8989
std::string BmffImage::toAscii(uint32_t n) {
90-
const auto p = reinterpret_cast<const char*>(&n);
91-
std::string result(p, p + 4);
92-
if (!isBigEndianPlatform())
93-
std::reverse(result.begin(), result.end());
94-
// show 0 as _
95-
std::replace(result.begin(), result.end(), '\0', '_');
96-
// show non 7-bit printable ascii as .
97-
auto f = [](unsigned char c) { return c < 32 || c > 126; };
98-
std::replace_if(result.begin(), result.end(), f, '.');
90+
std::string result(sizeof(uint32_t), '\0');
91+
for (size_t i = 0; i < result.size(); ++i) {
92+
auto c = static_cast<unsigned char>(n >> (8 * (3 - i)));
93+
if (c == 0)
94+
result[i] = '_';
95+
else if (c < 32 || c > 126)
96+
result[i] = '.';
97+
else
98+
result[i] = static_cast<char>(c);
99+
}
99100
return result;
100101
}
101102

src/jp2image.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,11 @@ Jp2Image::Jp2Image(BasicIo::UniquePtr io, bool create) : Image(ImageType::jp2, m
112112

113113
// Obtains the ascii version from the box.type
114114
std::string Jp2Image::toAscii(uint32_t n) {
115-
const auto p = reinterpret_cast<const char*>(&n);
116-
std::string result(p, p + 4);
117-
if (isBigEndianPlatform())
118-
return result;
119-
std::reverse(result.begin(), result.end());
115+
std::string result(sizeof(uint32_t), '\0');
116+
for (size_t i = 0; i < result.size(); ++i) {
117+
auto c = static_cast<unsigned char>(n >> (8 * (3 - i)));
118+
result[i] = static_cast<char>(c);
119+
}
120120
return result;
121121
}
122122

0 commit comments

Comments
 (0)