【问题标题】:c++ - How to convert char * buffer to unsigned short int * bufferShc++ - 如何将 char * buffer 转换为 unsigned short int * bufferSh
【发布时间】:2014-01-02 10:21:57
【问题描述】:

如何将 char buffer 转换为 unsigned short int newBuffer? 以下是我的代码:

另外,在生成的新缓冲区中,如何获取大小。 我正在读取 char buffer 中的图像文件,为了进一步处理,我想将此 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 代码,你确定要 C++ 答案吗?
  • 您面临的具体问题是什么?

标签: c++


【解决方案1】:

在C++中最好使用reinterpret_cast进行指针转换:

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

对于大小,您已经获得了它,因此您只需针对要转换为的类型的大小进行规范化:

int jp2shortsize = lSize * sizeof(char) / sizeof(unsigned short int);

【讨论】:

  • 如果您发现答案有帮助,您可以投票和/或接受它。阅读更多:meta.stackexchange.com/questions/5234/…。干杯!
  • 如何从指针数组中获取缓冲区的大小?假设我有以下数组: unsigned short int* ptrA // 一些值。 int size = sizeof(ptrA);
  • 你不能从指向数组的指针获取缓冲区的大小(除非你严重滥用它)。您必须在缓冲区旁边保持长度,使用一些常量或切换到 C++(或类似)中的 std::vector 类。
【解决方案2】:

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

【讨论】:

  • 感谢您快速有用的回复。
猜你喜欢
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多