In C language, how to determine whether the host is big or small (byte-order)

Source: Internet
Author: User

Http://www.cnblogs.com/52php/p/6114643.html

The so-called big-endian refers to the high value in memory put low address, so-called small end refers to low value in memory put low address. For example, 0x12345678 on the big-endian machine is 12345678, on the small end machine is 78564312, and a host is big or small end to look at the CPU type and running on the operating system. The same CPU in different operating systems use the size of the end case is different. Of course we usually use x86 + windows as the small end.

The test size end typically uses the Union feature. Union is a union in which all variables are common to a piece of memory, but are interpreted differently at different times. It stores in memory the number of bits required by the longest variable to open up memory

#include <stdio.h>

#include <stdbool.h> union {      int number;      char s; } test; bool testBigEndin() {      test.number = 0x01000002;      return (test.s == 0x01); } int main( int argc,  char **argv) {      if (testBigEndin()) {          printf ( "big" );      else {          printf ( "small" );      } }

My Mac output: Small

where the actual memory length of union is int, that is, a word, which is 32 bits on a 32-bit machine. Char is a byte (8-bit) and only takes the first low address byte. So its value can be used to determine the size of the end.

Warm tip: When the computer reads the memory data, it is (from left to right) from the low address to the high address

In C language, how to determine whether the host is big or small (byte-order)

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.