Write uint16_t to binary file with ofstream
I am trying to test writing some data to a file.
si开发者_Python百科xteenBitData = (uint16_t*) malloc(sizeof(uint16_t)*bufSizeX*bufSizeY);
memset(sixteenBitData, 1, sizeof(uint16_t)*bufSizeX*bufSizeY);
binfile->write((char *)&sixteenBitData, sizeof(uint16_t)*bufSizeX*bufSizeY);
as you can see, sixteenBitData is an array of uint16_t
I would expect my binary file to have a bunch of 1's it, but when I am loading it into matlab, it seems to have various numbers between 0 and 65535
Am I doing something wrong?
Thanks
1) sixteenBitData is a pointer. When you write, you take the address of the pointer which is somewhere on the stack, and then convert that to a char*, and write everything there to your file. I'm surprised it didn't crash.
2) memset sets each byte to the value of one. Since (I assume) uint16_t is two bytes, it's getting set to 0x0101, which is 257.
sixteenBitData = (uint16_t*) malloc(sizeof(uint16_t)*bufSizeX*bufSizeY);
for(int i=0; i<bufSizeX*bufSizeY; ++i)
sixteenBitData[i] = 1; //obvious replacement here
binfile->write((char *) sixteenBitData, sizeof(uint16_t)*bufSizeX*bufSizeY);
^
& removed
memset
inf sixteenBitData to 1 won't set each component in the array to 1, but to 257. What's more, you are writing the array as binary, does matlab open the file as binary or text?
精彩评论