How to copy an integer from a <char> vector

Now I am working on wav files, I am parsing them. At the moment, I do not want to use libraries. I open a wav file with fstream and read all the data into a vector. Now I want to parse the wav file header. For example, I want to get the size of a file that is between the 4th and 8th bytes. I want to assign this integer. I would do this with memcpy easily. But since it is C ++, I do not want to use memcpy. The solution ultimately:

std::vector<unsigned char>::iterator vectorIte = soundFileDataVec.begin(); vawParams.totalfilesize = 0; //Since it is little endian I used reverse_copy std::reverse_copy(vectorIte + 4, vectorIte + 7, (unsigned char*)&vawParams.totalfilesize); 

I'm not happy with (unsigned char *) cast on an integer pointer. I suspect there is a better way than me. Could you advise me the best way?

+4
source share
2 answers

Vectors use adjacent storage locations for their elements; their elements can be accessed using offsets on regular pointers to their elements. Therefore, if you do not want memcpy , then a trivial solution:

 int header = *reinterpret_cast<const int*>(&soundFileDataVec[4]); 

This reads you four bytes (you may need to convert from one continent to another).

+6
source

Once you are in the realm of binary serialization, if you want to be portable and you do not want to use the library, you should pretty much get below the abstraction levels of how the type of programming language will be presented to you. You must understand exactly how it is stored in a file, and you must understand exactly how to return it and translate it into a representation of the types that you have on your compiler, on the platform that you are compiling.

Trying to avoid throws is probably inherently wrong in these limitations.

+2
source

Source: https://habr.com/ru/post/1492583/


All Articles