Convert array of char[] to bytes and then convert bytes to int and vise versa

How to convert 4 characters “HERE” to a 4-byte integer that has the value 1163019592?

Here is what I tried:

int main()
{
    string s = "HERE";
    int n = s.length();

    int* number = new int[n + 1];
    char* cstr = new char[n+1];

    for (int i = 0; i < n; i++) {
        cstr[i] = s[i];
        number[i] = cstr[i];
        cout << number[i];
    }
}

but instead of 1163019592, I get 72698269.

Upvotes: 0

Views: 69

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595369

Decimal 1163019592 is binary 01000101 01010010 01000101 01001000, which is hex 0x45 0x52 0x45 0x48.

"HERE" is bytes 0x48 0x45 0x52 0x45.

Same bytes, different order.

If you want "HERE" to equate to 1163019592 without regard to endian, try this:

int main()
{
    string s = "HERE";
    size_t n = s.length();

    uint32_t number = 0;

    for (int i = 0; i < n; i++) {
        number = (number << 8) | static_cast<uint8_t>(s[n-i-1]);
    }

    cout << number;
}

Live demo

Upvotes: 1

Related Questions