i have tried this
char c[4];
int i=89;
memcpy(&c[0],&i,4);
cout<<(int)c[0]<<endl;
cout<<(int)c[1]<<endl;
cout<<(int)c[2]<<endl;
cout<<(int)c[3]<<endl;
the output is like:
89
0
0
0
which pretty trains my stomache cuz i thought the number would be saved in memory like 0x00000059 so how come c[0] is 89 ? i thought it is supposed to be in c[3]...
1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.
A byte can store a numerical value between 0 and 255 or between -127 and 127 if we are considering the negative numbers too. For the purposes of storing numerical data values, bytes are grouped together into words, which are typically 2 bytes. Data units of 512 bytes or more are called data blocks.
Data is represented on modern storage media using the binary numeral system. All data stored on storage media – whether that's hard disk drives (HDDs), solid state drives (SSDs), external hard drives, USB flash drives, SD cards etc – can be converted to a string of bits, otherwise known as binary digits.
All Java integer types are stored in signed two's complement format. The sign takes up one bit. The remaining bits store the value itself and dictate the range of values that can be stored for each type. For example, a short value uses one bit for the sign and 15 bits to store the value.
Because the processor you are running on is little-endian. The byte order, of a multi-byte fundamental type, is swapped. On a big-endian machine it would be as you expect.
This is because you're running the program on a little endian cpu. See also endianness here and there.
Endian-ness is obviously the answer as Goz has pointed out.
But for those who are unclear of what that means, it's also important to understand that the order of bytes displayed in the example is the same as the order in the original int. Memcpy doesn't change the byte order, regardless of the edian type of the platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With