Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy an integer from vector<char>

Tags:

c++

stdvector

I am working now on wav files, I am tring parse them. I don't wanna use libraries for now . I open the wav file with fstream and read all the data to vector. Now I want to parse wav file header . For example I want to get filesize which is between 4th and 8th bytes. I want to assign this to a integer . I would accomplish this with memcpy easily .But since it is C++ I don't wanna use memcpy. The solution I end up with :

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 am not happy with (unsigned char*) cast to integer pointer .I suspect there is a better way than I do. Can you please advice me a better way?

like image 265
Kadir Erdem Demir Avatar asked Feb 16 '23 20:02

Kadir Erdem Demir


1 Answers

Vectors use contiguous storage locations for their elements, their elements can be accessed using offsets on regular pointers to its elements. So if you don't want a memcpy then a trivial solution is:

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

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

like image 98
emesx Avatar answered Feb 18 '23 10:02

emesx