[英]Converting double to unsigned char?
I'm trying to convert a matrix of (doubles) into an unsigned char so I can then write to a .pmg file... But it isn't working. 我正在尝试将(double)的矩阵转换为无符号字符,以便随后可以写入.pmg文件...但是它不起作用。
void writePNG(vector<double>& matrix)
{
vector<unsigned char> image;
ofstream myfile;
myfile.open("newFile.txt", ios::out); // writing to .txt file for now for testing.
if(!myfile.is_open())
{
cout << "Cannot open file";
}
for(int i=0; (i < 512*512); i++)
{
image[i] = (unsigned char) matrix[i];
}
myfile.close();
}
It won't convert the data. 它不会转换数据。 Any ideas?? 有任何想法吗?? Thanks :) 谢谢 :)
fstream
object goes out of scope 当fstream
对象超出范围时,它将关闭 vector::vector
displays your intent more clearly. 使用vector::vector
可以更清楚地显示您的意图。 Try this: 尝试这个:
#include <vector>
#include <iostream>
#include <fstream>
void writePNG(const std::vector<double>& matrix)
{
std::ofstream myfile("newFile.txt", std::ios::out);
if(!myfile.is_open())
{
std::cout << "Cannot open file";
}
std::vector<unsigned char> image (matrix.begin(), matrix.end());
myfile.write(reinterpret_cast<const char*>(&image[0]), image.size());
}
int main () {
writePNG({
72, 101, 108.1, 108.2,
111, 0x2c, 0x20, 0x77,
0x6f, 0x72, 0x6c,
100.3, 10.4});
}
You are creating image
using the default constructor of vector
, which initializes the vector as empty (containing no elements). 您正在使用vector
的默认构造函数创建image
,该构造函数将vector
初始化为空(不包含任何元素)。 The subscript notation ( image[i]
) does not create an element, only assigns to an already exising one. 下标符号( image[i]
)不创建元素,仅分配给已经存在的元素。
You have (at least) two ways to fix it: 您有(至少)两种方法来修复它:
image
using the ctor of vector
that allocates the necessary size: vector<unsigned char> image(512*512)
-- this will populate the vector with 512*512 elements of default value (0 for unsigned char
) 使用分配必要大小的vector
的ctor声明image
: vector<unsigned char> image(512*512)
-这将使用默认值的512 * 512个元素( unsigned char
为0)填充向量 push_back
method: image.push_back((unsigned char) matrix[i]);
使用push_back
方法一一添加元素: image.push_back((unsigned char) matrix[i]);
You also will have to write the contents of image
to myfile
eventually. 您最终还必须将image
的内容写入myfile
。
Note: it is a good habit to use static_cast<unsigned char>(...)
instead of the C-style (unsigned char) ...
as the former can find errors that the latter will not flag; 注意:使用static_cast<unsigned char>(...)
而不是C样式(unsigned char) ...
是一个好习惯,因为前者会发现后者不会标记的错误; this is not an issue in this particular case, though 在这种情况下,这不是问题
You image vector has zero size - you would have to at least do a push_back to add an element. 您的图片矢量大小为零-您至少必须执行push_back才能添加元素。 Also, the size of a double is not the same size of a char so you are going to lose information. 同样,双精度数的大小与char的大小不同,因此您将丢失信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.