lundi 15 février 2021

C++ convert char array read from a binary file into an integer

Following code is to read 4 bytes from a binary file, to store the value in an char array, then convert it to an integer. It works well, but I just wonder why or how the last code line can work, i.e. result = (int)r_buff[3] + ((int)r_buff[2]<< 8) + ((int)r_buff[1]<<16) + ((int)r_buff[0]<<24);.

2nd, What is the symbol << doing here?

3rd, any better substitute codes of this?

Many thanks.

The source I saw was originally from http://www.cplusplus.com/forum/beginner/16887/.

int buf_size = 4;   
char r_buff[buf_size-1];
int result;

string b_file = "my_binary_file.bin";
ifstream reader;
reader.open(b_file , ios::in | ios::binary);
reader.read(r_buff, buf_size);

result = (int)r_buff[3] + ((int)r_buff[2]<< 8) + ((int)r_buff[1]<<16) + ((int)r_buff[0]<<24);

Aucun commentaire:

Enregistrer un commentaire