[英]Hex to JPG conversion in C++
我正在編寫一個 C++ 程序,我需要轉換一些基本上是十六進制格式的字符串輸出。 此輸出字符串以 FFD8 開頭並以 FFD9 結尾,它基本上是一個 JPEG 圖像。
現在,我想從該字符串輸出中獲取 JPEG 文件,但我不想將該字符串輸出保存在文本文件中並以 ios::binary 模式打開它,然后將其轉換為 JPEG 文件。
std::string output; //which is FFD8..........FFD9
//******some code*******???
ofstream imageFile;
imageFile.open('Image.jpg');
imageFile<< output;
如何在不將字符串輸出保存在文件中的情況下做到這一點?
提前致謝!
我的假設是,您有一個表示十六進制的字符串,並且要將其轉換為等效的字節。
byte hexCharToByte(const char h){
if(isdigit(h))
return h - '0';
else
return toupper(h) - 'A' + 10;
}
這是我用C編寫的一些代碼,它使用一個char並將其轉換為字節。 您可以根據需要進行調整。
這個怎么運作:
std::string output; //which is FFD8..........FFD9
int main()
{
std::ofstream thum("name.jpg", std::ios_base::binary | std::ios_base::out);
char buf[3];
buf[2] = 0;
std::stringstream in(output);
in.flags(std::ios_base::hex);
while (in)
{
in >> buf[0] >> buf[1];
long val = strtol(buf, nullptr, 16);
thum << static_cast<unsigned char>(val & 0xFF);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.