C ++: how to convert an int into four bytes ?, Int bytes
As we all know, an int or unsigned int is composed of four bytes (C/C ++ Learning Guide, Chapter 3rd, section 3.2.3: Memory view of variables)
For example,
Int n = sizeof (int); // n is 4
You can also clearly see the four bytes in the memory. (C/C ++ Learning Guide, Appendix: VC2008 debugging method)
But the question is: how to convert the code into four bytes?
Method 1: memcpy
This method is violent and unscientific. Try it first.
Unsigned int a = 0x12345678;
Unsigned char buf [4];
Memcpy (buf, & a, 4 );
Check whether the value of the four elements in the buf array is 0x78 0x56 0x34 0x12 (well, small end, this is a defect, the expected result is actually buf [0] = 0x12 buf [1] = 0x34 buf [2] = 0x56 buf [4] = 0x78)
Method 2: formal method (C/C ++ Learning Guide, Chapter 1, Section 6th)
Buf [0] = a> 24;
Buf [1] = a> 16;
Buf [2] = a> 8;
Buf [3] =;
Use your VC to see if it is your intention. Check it in the debugging status. Do not use printf any more.
No thanks, you should!