如何将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);
答案 0 :(得分:1)
最好在C ++中使用reinterpret_cast
来进行指针转换:
unsigned short int* ptrA = reinterpret_cast<unsigned short int*>(ptrB);
对于大小,您已经获得了它,因此您只需要规范化您要转换为的类型的大小:
int jp2shortsize = lSize * sizeof(char) / sizeof(unsigned short int);
答案 1 :(得分:0)
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