C ++: how to convert an int into four bytes ?, Int bytes

Source: Internet
Author: User

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!






 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.