Browse - Computer Tips - C/C++ Check if a vector of bytes is a PNG

Date: 2019jan21
Language: C/C++

Q.  C/C++ Check if a vector of bytes is a PNG

A.  Check it starts with the magic string.

bool isPng(const std::vector<std::byte> &ba) { const std::byte magic[] = { 0x89, 'P', 'N', 'G' }; const int magicLen = sizeof(magic) / sizeof(magic[0]); if (ba.size() < magicLen) return false; for (int i = 0; i < magicLen; i++ ) { if (ba[i] != magic[i]) return false; } return true; }