I know that if the integer is dissected rather than being computed as a whole, the total of individual bytes will yield incorrect result. However, for curiosity, I want to examine individual byte and make.I’m not sure if this is correct to inspect each byte in an integer pointer:
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
int *num = new int;
*num = 123456789;
cout << "Num: " << *num << '\n';
char* numchar_ptr = reinterpret_cast<char*> (num);
for (int i = 0; i < 4; ++i)
{
cout << "number char: " << i << ' ' << (short) *(numchar_ptr+i) << '\n';
*(numchar_ptr+i) = i
}
cout << "New num: " << *num << '\n';
delete num;
return 0;
}
According to the loop, the bytes in the integer will be: 0 1 2 3
which is equal to 00000000 00000001 00000010 00000011 in binary and 66051 in decimal
But I got the result “New num” is 50462976. Why?
You need to take endianness into account. On your system, numbers are stored in little-endian representation, which means that the lowest-addressed byte is the least-significant.
Therefore, your number is:
which is 50462976.