2015-02-06 13 views
-4

標題是我的問題 - 我將如何去翻轉已從文件加載的std :: ifstream中的所有位?C++反轉fstream中的所有位

ifstream file("filename.png"); 

if (!file.is_open()) { 
    return false; 
} 

我不知道我應該從這裏出發。通過翻轉,我指的反轉位(0,如果1,1,如果0)

+0

首先讀取一些獨立於翻轉的字節,將每個字節翻轉一個獨立於文件的循環。問題在哪裏? – deviantfan 2015-02-06 19:33:02

+4

除了打開文件之外,你有沒有嘗試過任何東西? – 2015-02-06 19:33:19

+0

@你是什麼意思_「我將如何去翻轉所有位」 _翻轉位實際? ['的std :: ifstream的::明確()'](http://en.cppreference.com/w/cpp/io/basic_ios/clear)? – 2015-02-06 19:41:05

回答

2

這是X-Y的問題。我真的懷疑你想要翻轉PNG格式文件中的所有位,只是因爲文件中除了位圖位之外還有其他字段。此外,除非該圖像是純黑色&白色,還有更多的比反轉比特的顏色比特。

這就是說,這裏是如何翻轉這些位。反轉像素
大多數圖像由像素或圖像元素的

While not the end of the file, do: 
    read a block of bytes (uint8_t) 
    for each byte read do: 
    read the byte 
    invert the byte (a.k.a. using `~` operator) 
    store the byte 
    end-for 
    write block to new file. 
end-while 

副作用。這些元素通常用每個像素的位數來表示,如果多種顏色,每種顏色的位數。

讓我們舉例來說一個每像素24位的RGB圖像。這意味着有8位表示紅色,8位表示綠色,8位表示藍色。每種顏色的取值範圍爲0到255.這表示顏色的數量。

讓我們取1個顏色,綠色,值爲0x55或二進制0101 0101.反轉(翻轉)位將產生0xAA或1010 1010的值。所以在翻轉綠色值後,現在是0xAA。

如果這是你希望發生的事情,對每個像素改變顏色的量的,那麼你就需要從圖像的PNG文件中提取顏色數量和反轉它們。

1

下面是做這件事:

#include <fstream> 

int main(int argc, char **argv) 
{ 
    std::ifstream ifile(argv[1]); /// input 
    std::ofstream ofile(argv[2]); /// output 

    if (ifile.is_open() && ofile.is_open()) { 
     char ch; 
     std::string data = ""; 

     while (ifile.get(ch)) { 
      for (unsigned int i = 0; i < 8; ++i) 
       ch ^= (1 << i); 
      data += ch; 
     } 
     ofile << data; 
    } 
    ifile.close(); 
    ofile.close(); 
    return 0; 
} 

用法:

./prog input output 

輸入:

$ xxd -b input 
0000000: 00110001 00110000 00110000 00110001 00001010 

輸出:

$ xxd -b output 
0000000: 11001110 11001111 11001111 11001110 11110101