使用c++98实现:vector<uint8_t> img中,前四字节装int a = 1585,第四到第八字节装int b = 1568,第八字节后装一张图像经过cv::imencode()后的数据,再从img中反向取出以上数据,a,b和图像数据
时间: 2024-03-14 21:44:43 浏览: 23
以下是使用C++98实现的代码示例:
```c++
#include <iostream>
#include <vector>
#include <stdint.h>
#include <opencv2/opencv.hpp>
int main()
{
// 定义变量a和b
int a = 1585, b = 1568;
// 读取图像
cv::Mat img = cv::imread("test.jpg");
// 对图像进行编码
std::vector<uint8_t> img_data;
cv::imencode(".jpg", img, img_data);
// 将a和b转换为字节数组
uint8_t a_bytes[4], b_bytes[4];
*(int*)a_bytes = a;
*(int*)b_bytes = b;
// 将a、b和图像数据合并到一个向量中
std::vector<uint8_t> result;
result.reserve(8 + img_data.size());
for (int i = 0; i < 4; ++i) result.push_back(a_bytes[i]);
for (int i = 0; i < 4; ++i) result.push_back(b_bytes[i]);
result.insert(result.end(), img_data.begin(), img_data.end());
// 从向量中反向取出a、b和图像数据
uint8_t a_bytes_out[4], b_bytes_out[4];
for (int i = 0; i < 4; ++i) a_bytes_out[i] = result[i];
for (int i = 0; i < 4; ++i) b_bytes_out[i] = result[4 + i];
int a_out = *(int*)a_bytes_out;
int b_out = *(int*)b_bytes_out;
std::vector<uint8_t> img_data_out(result.begin() + 8, result.end());
// 输出结果
std::cout << "a: " << a_out << std::endl;
std::cout << "b: " << b_out << std::endl;
std::cout << "img size: " << img_data_out.size() << std::endl;
return 0;
}
```
注意,上述代码中的`*(int*)a_bytes`和`*(int*)b_bytes`都是强制类型转换,将字节数组转换为整型。这种写法在C++98中是允许的,但是在C++11及以后的版本中被认为是不安全的。如果在实际开发中使用,请谨慎考虑。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)