C++ c++;-如何将char*buffer转换为无符号短int*bufferSh

C++ c++;-如何将char*buffer转换为无符号短int*bufferSh,c++,C++,如何将字符缓冲区转换为无符号短整型新缓冲区? 下面是我的代码: 另外,在生成的newbuffer中,如何获得大小。 我正在读取字符缓冲区中的图像文件,为了进一步处理,我想将该字符转换为无符号短int*。 请有人帮我解决这个问题 FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen ( "d:\\IMG1" , "rb" ); if (pFile==NULL) {fputs ("File error",stder

如何将字符缓冲区转换为无符号短整型新缓冲区? 下面是我的代码:

另外,在生成的newbuffer中,如何获得大小。 我正在读取字符缓冲区中的图像文件,为了进一步处理,我想将该字符转换为无符号短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++中使用<代码> RealTytCase< /Cult>进行指针转换:

unsigned short int* ptrA = reinterpret_cast<unsigned short int*>(ptrB);

fread
函数不需要字符缓冲区,它接受
void*
,因此您不需要强制转换:

size_t const jp2shortsize = lSize / sizeof(unsigned short int);
unsigned short int * shBuffer = (unsigned short int *) malloc(sizeof(unsigned short int) * jp2shortsize);
result = fread(shBuffer, sizeof(unsigned short int), jp2shortsize, pFile); // mind endianess here

这看起来更像C代码,你确定你想要C++答案吗?你面临的具体问题是什么?谢谢你的回答。如果你发现答案是有用的,你可以投票和/或接受它。更多信息请访问:。干杯如何从指针数组中获取缓冲区的大小?假设我有以下数组:unsigned short int*ptrA//Some value。int size=sizeof(ptrA);您无法从指向数组的指针获取缓冲区的大小(除非您严重滥用它)。你必须与缓冲区保持一定的长度,使用一些常量,或者切换到STD::向量类在C++中(或类似的)。谢谢你的快速有用的响应。
size_t const jp2shortsize = lSize / sizeof(unsigned short int);
unsigned short int * shBuffer = (unsigned short int *) malloc(sizeof(unsigned short int) * jp2shortsize);
result = fread(shBuffer, sizeof(unsigned short int), jp2shortsize, pFile); // mind endianess here