Picture.pbm -->十进制,在 c++ 中
Picture.pbm --> decimal, in c++
只是想问是否有人知道为什么我不能将整个图片转换为十进制。
问题:大约 180 次后,其余像素变为 0。
法典:
#include <fstream>
#include <iostream>
int main() {
char unsigned charTemp = 0;
int unsigned intTemp = 0;
std::fstream file;
file.open("PIC.pbm", std::ios::in);
//Ignore header
for (int i = 0; i < 13; i++) {
file.ignore();
}
//read and print
//img res is 40x40 = 1600
for (int i = 0; i < 1600; i++) {
file >> charTemp;
intTemp = charTemp;
std::cout << intTemp << " ";
charTemp = 0;
intTemp = 0;
}
std::cout << "nnn";
system("pause");
return 0;
}
图片:任何 40x40 pbm
图片和图像文件的更好方法是将它们读取为binary
文件:
std::ifstream file("PIC.pbm", ios::binary);
std::vector<unsigned char> bitmap(1600);
// Skip over the header
file.seekg(13, ios::beg); // Skip over 13 bytes.
// Read in the data at once
file.read((char *) &bitmap[0], 1600);
// Now process the bitmap from memory
for (int i = 0; i < 1600; ++i)
{
cout << static_cast<unsigned int>(bitmap[i]) << " ";
if ((i % 40) == 39)
{
cout << "n";
}
}
cout << "n";
这里的想法是将一个事务中的位图读入内存。 流喜欢流动(不要中断流(。 内存的访问速度比文件快,因此位图值是从内存中处理的。
使用强制转换,以便格式化插入不会将字节视为字符,而是将数字视为数字。
首先,在另一个十六进制编辑器中打开您的PIC.pbm
文件,因为这些字节很可能真的是零。如果没有,那么您在读取文件时遇到问题。
fstream
构造函数不默认以二进制模式读取,因此它将文件读取为"文本" - 我已经学到了艰难的方式,你不能再相信标准库对文本有任何了解(如何处理 Unicode、行尾等 - 我觉得最好始终使用 binary
和专用的 Unicode 库(。
您应该在每次读取操作后检查 fstream::good()
函数以查看它是否失败,如果是,请检查iostate
:
using namespace std;
// ...
fstream file;
file.open( "PIC.pbm", ios::in | ios::binary );
file.ignore( 13 );
for (int i = 0; i < 1600; i++) {
file >> charTemp;
if( !file.good() ) {
cout << endl;
cout << "Error reading file: iostate == " << file.iostate << endl;
break;
}
else {
intTemp = charTemp;
std::cout << intTemp << " ";
charTemp = 0;
intTemp = 0;
}
}
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- 计算十进制 c++ 之后的数字
- C++从二进制转换为十进制数
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- cin 的十进制输入验证?
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 将分数转换为十进制数并对其进行排序
- uint8_t同一二进制文件的不同十进制值
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- 调用方如何知道 VARIANT 中何时有十进制?
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 十进制到二进制转换器 c++
- 使用标准库计算字符串中的十进制数
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 如何计算整数的十进制数字?
- (第 1 位 + 第 2 位)以十进制数表示
- 在 C++ 中使用带有十六进制十进制和八进制数的 unsetf