开发者

Write uint16_t to binary file with ofstream

开发者 https://www.devze.com 2023-04-05 00:50 出处:网络
I am trying to test writing some data to a file. si开发者_Python百科xteenBitData = (uint16_t*) malloc(sizeof(uint16_t)*bufSizeX*bufSizeY);

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 


memsetinf 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消