C + +: How to turn an int into 4 bytes?

Source: Internet
Author: User

As you all know, an int or unsigned int is made up of 4 bytes, (The Learning Guide for C/s + +, chapter 3rd, section 3.2.3: Memory view of variables)

For example

int n = sizeof (int); N is 4


It is also clear to see in memory, that 4 bytes is there, (the "C + + Learning Guide", Appendix: VC2008 Debugging Method)

But the question is: How do you turn the code into 4 bytes?


Method 1:memcpy

This method is violent and unscientific. Let's try it first.

unsigned int a = 0x12345678;

unsigned char buf[4];

memcpy (buf, &a, 4);

Observe the value of the 4 elements of the BUF array, is not 0x78 0x56 0x34 0x12 (well, small end, this is the flaw, we want the result is actually buf[0]=0x12 buf[1]=0x34 buf[2]=0x56 buf[4]=0x78)


Method 2: Formal Methods ("C + + Learning Guide", chapter 6th, section 6.8)

Buf[0] = a >> 24;

BUF[1] = a >> 16;

BUF[2] = a >> 8;

BUF[3] = A;

Use your VC to see if it is right for you. Look directly in the debug state, stop printf.


No thanks, it's supposed to be!






C + +: How to turn an int into 4 bytes?

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.