parsing - Convert bytes from a file to an integer c++ -


i trying parse .dat file reading byte byte code.(the name of file in arv[1])

   std::ifstream (arv[1], std::ifstream::binary);       if (is) {          is.seekg (0, is.end);         int length = is.tellg();         is.seekg (0, is.beg);          char * buffer = new char [length];          is.read (buffer,length);          if (is)           std::cout << "all characters read successfully.";         else           std::cout << "error: " << is.gcount() << " read";         is.close();     } 

now file in buffer variable. file contains numbers represented in 32 bits, how can iterate on buffer reading 4 bytes @ time , convert them integer?

first of , have memory leak, dynamically allocate character array never delete[] them. use std::string instead:

std::string buffer(length,0); is.read (&buffer[0],length); 

now, assuming had written integer correctly, , have read correctly buffer, can use character array pointer integer:

int myint = *(int*)&buffer[0]; 

(do understand why?) if have more 1 integer stored:

std::vector<int> integers; (int i=0;i<buffer.size();i+=sizeof(int)){  integers.push_back(*(int*)&buffer[i]); } 

Comments