繁体   English   中英

如何将char *缓冲区转换为unsigned short int * bufferSh

[英]c++ - How to convert char * buffer to unsigned short int * bufferSh

如何将char 缓冲区转换为unsigned short int newBuffer? 下面是我的代码:

另外,在生成的newbuffer中,如何获取大小。 我正在读取char 缓冲区中的Image文件, 并进行进一步处理,我想将此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);

fread函数不需要char缓冲区,它接受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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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