c++ - 如何将 char * buffer 转换为 unsigned short int * bufferSh

标签 c++

如何将 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/

相关文章:

c++ - 为什么这个 while 循环不退出?

c++ - 返回带有 getter 函数的成员对象作为 const 但它是可修改的

c++ - 为什么 regex_search 不需要命名空间

面向 C# 开发人员的 C++

c++ - 如何将几乎任何东西传递给 C++(或 C)中的函数?

C++ fscanf() 返回 -1 并且不覆盖变量

c++ - 外部变量在 visual studio 中重置自身

c++ - 错误 : boost/scoped_ptr. hpp:使用 libkml 时没有这样的文件或目录

c++ - 在构造函数中使用对象

c++ - 如何调用boost_compute 'BOOST_COMPUTE_FUNCTION'定义的函数?