Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ byte array to int

Tags:

c++

Now there is a unsigned char bytes[4] and I've already known that the byte array is generated from an int in C++. How can I convert the array back to int?

like image 544
maxwellhertz Avatar asked Sep 25 '18 06:09

maxwellhertz


2 Answers

You can do that using std::memcpy():

#include <iostream>
#include <cstring>

int main() {
    unsigned char bytes[4]{ 0xdd, 0xcc, 0xbb, 0xaa };

    int value;
    std::memcpy(&value, bytes, sizeof(int));

    std::cout << std::hex << value << '\n';
}
like image 183
Swordfish Avatar answered Nov 15 '22 11:11

Swordfish


I've already known that the byte array is generated from an int in C++.

It is crucial to know how the array is generated from an int. If the array was generated by simply copying the bytes on the same CPU, then you can convert back by simply copying:

int value;
assert(sizeof value == sizeof bytes);
std::memcpy(&value, bytes, sizeof bytes);

However, if the array may follow another representation than what your CPU uses (for example, if you've received the array from another computer, over the network), then you must convert the representation. In order to convert the representation, you must know what representation the source data follows.

Theoretically, you would need to handle different sign representations, but in practice, 2's complement is fairly ubiquitous. A consideration that is actually relevant in practice is the byte-endianness.

like image 5
eerorika Avatar answered Nov 15 '22 10:11

eerorika