Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a char array to an integer

Tags:

c++

Basically I am reading a binary format where 4 bytes specify the size of the string to follow. So i want to cast 4 chars I am reading from a buffer to 1 integer.

Here is what I have.

int FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
  //skip the marker and read next 4 byes
  int cursor = cursor + 4; //skip marker and read 4
  char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};
  int32_t objSize = tmpbuffer;
  return objSize;

}

thoughts?

like image 485
j_mcnally Avatar asked Nov 18 '25 06:11

j_mcnally


1 Answers

It's pretty easy to do the unpacking manually:

unsigned char *ptr = (unsigned char *)(buffer + cursor);
// unpack big-endian order
int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
like image 184
nneonneo Avatar answered Nov 20 '25 21:11

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!