How to store 4 bytes of long data in a character array?

Source: Internet
Author: User

/* Prerequisite */<br/> long a = 0x12345678; <br/> char s [5] = {0 }; </P> <p>/* method 1 */<br/>/* principle: Take the address of a and forcibly convert it to char *. (The pointer occupies one byte, exactly four bytes), then unreference the value and assign it to s [I]; */<br/> for (INT I = 0; I <4; I ++) <br/>{< br/> S [I] = * (char *) & A + I ); <br/>}</P> <p>/* method 2 */<br/>/* principle: Convert the character array (4 bytes ), forcibly convert to long pointer, unreference, and assign values; */<br/> * (long) S =; </P> <p>/* method 3 */<br/>/* principle: use the library function to copy the memory; <br/> */<br/> memcpy (S, & A, 4 ); </P> <p>/* all three of them have the same effect */<br/> printf ("% x/N ", s [0], s [1], s [2], s [3]);

 

Of course, you also need to consider the size of the machine!

 

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.