嗨我正在讀取格式爲十六進制的二進制文件。它是一個圖像文件,下面是在Linux上使用hd ... | more命令的前幾行代碼的簡短示例。圖像是二進制圖形,所以唯一的像素顏色是黑色或白色。它是一個1024×1024的圖像,但尺寸爲2097152字節檢查原始文件的輸出C++
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | .......... ...... |
000dfbf0 00 00 00 00 00 00 00 00 00 00 00 00 ff 00 ff 00 | ................ |
000dfc00 ff 00 ff 00 ff 00 00 00 00 00 00 00 00 00 00 00 | ................ |
000dfc10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ |
這是我使用在另一個線程發現閱讀它的代碼工作然而代碼上SO
ifstream file (argv[1], ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize;
char* fileContents;
if(file.is_open())
{
fileSize = file.tellg();
fileContents = new char[fileSize];
file.seekg(0, ios::beg);
if(!file.read(fileContents, fileSize))
{
cout << "fail to read" << endl;
}
file.close();
cout << fileSize << endl;
當我運行for循環
for (i=0; i<2097152; i++)
printf("%hd",fileContents[i]);
唯一打印出來是零並且不是1。爲什麼這是我在printf中的參數沒有正確指定像素大小。我知道一個事實,即圖像中有1代表白色區域。另外我怎麼弄出多少字節代表這個圖像中的一個像素。
cout如何知道一次訪問2個字節並將它們更改爲十進制來表示像素值爲1或0 – user1084113
@ user1084113:'cout'會知道,因爲您將傳遞給它一個'short',而不是' char'。 'format()'把你傳達的值的大小作爲你傳遞的值的大小,並且你在說謊。 –