如何将 char buffer 转换为 unsigned short int newBuffer? 下面是我的代码:
另外,在生成的新缓冲区中,如何获取大小。 我正在读取 char 缓冲区中的图像文件,为了进一步处理,我想将此 char 转换为 unsigned short int *。 请有人帮我解决这个问题
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "d:\\IMG1" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
unsigned short int *shBuffer = (unsigned short int *)buffer;
int jp2shortsize = sizeof(*shBuffer);
free (buffer);
最佳答案
最好在 C++ 中使用 reinterpret_cast
进行指针转换:
unsigned short int* ptrA = reinterpret_cast<unsigned short int*>(ptrB);
对于大小,您已经获得了它,因此您只需要对要转换为的类型的大小进行归一化:
int jp2shortsize = lSize * sizeof(char) / sizeof(unsigned short int);
关于c++ - 如何将 char * buffer 转换为 unsigned short int * bufferSh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20880753/