Karuthedan
Karuthedan

Reputation: 93

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

How to convert char buffer to unsigned short int newBuffer? Below is my code:

Also, in the resulting newbuffer, how to get the size. I am reading an Image file in char buffer and for further processing, I want to convert this char to unsigned short int *. Please somebody help me to solve this

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);

Upvotes: 0

Views: 2471

Answers (2)

Greg
Greg

Reputation: 1660

fread function does not need char buffer, it accepts void *, so you do not need to cast:

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

Upvotes: 0

mockinterface
mockinterface

Reputation: 14880

It is better to use reinterpret_cast in C++ to do the pointer conversions:

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

For the size, you have already obtained it, so you'll just need to normalise for the size of the type you are converting to:

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

Upvotes: 1

Related Questions