简体   繁体   中英

converting char array to int using c++

Can anyone explain me how this code results 16843009 ? How it works?

As I saw in my tests, (int *)&x results 0x61ff1b and as I know that is the address of the first element in the array. and how the result of *(int *)&x is 16843009 ? Thanks.

#include <iostream>

using namespace std;


int main()
{
    char x[5] = {1, 1, 1, 1, 1};
    cout << *(int *)&x;

   return 0;;
}

If we write 16843009 as binary we get 1000000010000000100000001 . Padding that with extra zeros we get: 00000001000000010000000100000001 . Every 8 bits (which is a char) has a value of 00000001 , which is 1 .

&x is a pointer to an array of char (Specifically a char(*)[5] ). This is reinterpreted as a pointer to int. On your system, int is probably 4 bytes, and all four of those bytes are seperately set to 1, which means you get an int where every 8 bits are set to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM