简体   繁体   中英

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.

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 :)

  • bug : You are creating a vector of size 0, and then writing to its non-existent elements.
  • bug : You never write the data to a file
  • style : You close the file needlessly. It will be closed when the fstream object goes out of scope
  • style : You copy the data in a loop. Using vector::vector displays your intent more clearly.
  • potential bug : You create an output vector of 512x512, regardless of the size of the input vector.
  • SSCCE Your testcase is incomplete.

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). The subscript notation ( image[i] ) does not create an element, only assigns to an already exising one.

You have (at least) two ways to fix it:

  • declare 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 )
  • add the elements one-by-one using the push_back method: image.push_back((unsigned char) matrix[i]);

You also will have to write the contents of image to myfile eventually.

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; 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. Also, the size of a double is not the same size of a char so you are going to lose information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM