Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is each byte in an integer stored in CPU / memory?

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]...

like image 264
Pyjong Avatar asked Dec 03 '09 19:12

Pyjong


People also ask

How is an integer stored in computer memory?

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.

How is a byte 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.

How is data stored within a computer's memory?

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.

How integers are stored in memory in Java?

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.


3 Answers

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.

like image 152
Goz Avatar answered Oct 27 '22 00:10

Goz


This is because you're running the program on a little endian cpu. See also endianness here and there.

like image 29
Gregory Pakosz Avatar answered Oct 27 '22 00:10

Gregory Pakosz


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.

like image 24
Alan Avatar answered Oct 26 '22 22:10

Alan