在C++中加载位图时出现Big Endian问题
Loading Bitmap in C++ with Big-Endian issues
我目前正在Visual Studio中读取位图,其中包含以下代码:
unsigned char* imageIO::readBMP(char* filename) {
FILE* f = fopen(filename, "rb");
if (f == NULL)
{
printf("%s n", "File Not Loaded");
}
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); //read the 54-byte header
//extract image height and width from header
imageWidth = *(int*)&info[18];
imageHeight = *(int*)&info[22];
imageBytes = 3;
size = imageWidth * imageHeight * imageBytes;
unsigned char* readData = new unsigned char[size]; //allocate 3 byte per pixel
fread(readData, sizeof(unsigned char), size, f); //read the rest of the data at once
fclose(f);
return readData;
}
然而,我正试图让这段代码在PowerPC上运行,但它从位图标头中提取了错误的宽度和高度。我认为这与Little Endian(普通PC)和Big Endian(PowerPC)有关。
我应该如何在Big Endian机器上读取位图?
我可以翻转Little Endian数据吗?
您可以这样做(它应该适用于big-endian或little-endian架构):
unsigned int getIntLE(const unsigned char *p) {
#if LITTLE_ENDIAN
return *(unsigned int *)p;
#else
return ((unsigned int)p[3] << 24) |
((unsigned int)p[2] << 16) |
((unsigned int)p[1] << 8) |
p[0];
#endif
}
// ...
imageWidth = getIntLE(&info[18]);
imageHeight = getIntLE(&info[22]);
请注意,您需要定义LITTLE_ENDIAN
或使用Visual Studio预定义的内容。我手头没有Windows开发环境来了解那里使用了什么。
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 从值小于256的uint16到uint8的Endian安全转换
- 如何计算Big-O表示法中的平均渐近运行时间
- 嵌套在循环中的两个循环的 big-O 表示法
- 如何从Little Endian UTF-16编码字节中获取C++std::string
- 如何在C 中的Little Endian中读取来自二进制文件的单独的十六进制字符
- 此代码的 Big-O 表示法是什么?
- 正在使用Boost Endian算术类型被认为是好实践
- 计算Big-O运行时间
- 操作方法:将 boost::endian 缓冲区类型转换回本机格式
- 两种算法的Big-O分析
- 如何确定递归代码的Big-O
- 如何将Little-endian 64转换为C 中的主字节订单
- 如何从c 中的文件中读取小endian整数
- big-endian中的整数强制转换
- 如何在C++中从字节数组(在 BIG-ENDIAN 中)中提取单个字段
- 将数据转换为big-endian
- big和little endian浮点之间的区别是什么
- 在C++中加载位图时出现Big Endian问题
- Big Endian字节与字符串作为字符串数据库中的键