[英]Hex to JPG conversion in C++
I am writing a C++ program where I Need to convert some string output which is basically in HEX format.我正在编写一个 C++ 程序,我需要转换一些基本上是十六进制格式的字符串输出。 This output string starts with FFD8 and Ends with FFD9 which is basically a JPEG Image.
此输出字符串以 FFD8 开头并以 FFD9 结尾,它基本上是一个 JPEG 图像。
Now, I want to get the JPEG file from that string output but I don't want to save that string output in a text file and open it in ios::binary mode and then covert it to a JPEG file.现在,我想从该字符串输出中获取 JPEG 文件,但我不想将该字符串输出保存在文本文件中并以 ios::binary 模式打开它,然后将其转换为 JPEG 文件。
std::string output; //which is FFD8..........FFD9
//******some code*******???
ofstream imageFile;
imageFile.open('Image.jpg');
imageFile<< output;
How I can do that without saving my string output in a file?如何在不将字符串输出保存在文件中的情况下做到这一点?
Thanks in advance!提前致谢!
My assumption is that you have a string representing hex, and you want to convert that to the byte equivalent. 我的假设是,您有一个表示十六进制的字符串,并且要将其转换为等效的字节。
byte hexCharToByte(const char h){
if(isdigit(h))
return h - '0';
else
return toupper(h) - 'A' + 10;
}
This is some code I wrote a while back in C that takes a char and converts it to a byte. 这是我用C编写的一些代码,它使用一个char并将其转换为字节。 You can adapt it however you need.
您可以根据需要进行调整。
How it works: 这个怎么运作:
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.