前者010editor和HxD软件可以看
后者直接右键单击-属性-详细信息就能看到,鼠标悬停也会有
#include<iostream>
#include<fstream>
#include<string>
#include <iomanip>
#include <cstdint>
using namespace std;
/// @brief 文件以十六进制显示
/// @param filePath 文件路径
/// @param bytes_pre_line 每行显示字节数,默认为16
/// @param read_bytes 从文件头开始读取的字节总数,默认为0读取整个文件
void showHex(std::string filePath, unsigned int bytes_pre_line=16, unsigned long read_bytes=0)
{
std::ifstream fs;
fs.open(filePath, ios_base::binary|ios::ate);
if(!fs)
{
std::cerr << "无法打开文件" << std::endl;
exit(1);
}
unsigned long ReadBytes;
if(read_bytes)
{
ReadBytes = read_bytes;
} else
{
// fs.seekg(0, ios::end);
ReadBytes = fs.tellg();
}
fs.seekg(0, ios::beg);
char byte;
int i,nn=0;
std::string buf;
for(i=1;i<=ReadBytes;++i)
{
fs.get(byte);
buf += isprint(byte) ? byte : '.';
nn = (int)(byte) & 0xff;
std::cout << std::setfill('0') << std::setw(2) << std::hex << nn << " ";
if(i%bytes_pre_line==0)
{
std::cout << " | " << buf << std::endl;
buf = "";
}
}
if(i%bytes_pre_line != 1)
{
while(true)
{
std::cout << " ";
if(i%bytes_pre_line==0)
{
std::cout << " | " << buf << std::endl;
break;
}
++i;
}
}
fs.close();
}
/// @brief 对uint32_t按字节反转
/// @param x uint32_t *
void reverseBytes(uint32_t *x){
*x = (*x << 16) | (*x >> 16);
*x = ((*x & 0xff00ff00) >> 8) | ((*x & 0x00ff00ff) << 8);
}
/// @brief 获取PNG文件的宽和高
/// @param filePath PNG文件路径
/// @param width PNG文件的宽
/// @param height PNG文件的高
void getPngWidthHeight(std::string filePath, unsigned int * width, unsigned int * height)
{
std::ifstream fs;
fs.open(filePath, ios_base::binary);
if(!fs)
{
std::cerr << "无法打开文件" << std::endl;
exit(1);
}
fs.seekg(16L, ios::beg);
uint32_t * n;
fs.read((char *)n, 4);
reverseBytes(n); // 如果输出不正确可以试试把这一行去掉
*width = *n;
fs.read((char *)n, 4);
reverseBytes(n);
*height = *n;
}
int main(){
unsigned int w,h;
showHex("0.gif", 8);
getPngWidthHeight("0.png", &w, &h);
cout << w << "x" << h << endl;
return 0;
}
一个示例输出:
47 49 46 38 39 61 01 00 | GIF89a..
01 00 00 ff 00 2c 00 00 | .....,..
00 00 01 00 01 00 00 02 | ........
00 3b | .;
512x711