1024programmer Blog Big endian little endian: testing the native data storage form_trb331617’s blog

Big endian little endian: testing the native data storage form_trb331617’s blog

Little endian: the low bit of data is stored in the low address

Big endian:

This difference in data storage method is not caused by the operating system, but by the processor architecture.

 1 #include 
   2 
   3 int main(int argc, char *argv[])
   4 {
   5 int a = 0x12345678;
   6 char *p = (char *)&a;
   7 if(*p = 0x78)
   8 printf("little endian\n");
   9 else
  10 fprintf(stdout, "big endian\n");
  11
  12 return 0;
  13 }

 1 #include 
   2 
   3 /* Data storage form test function, big endian method returns 0, little endian method returns 1 */
   4 int test_endian(void)
   5 {
   6 int a = 0x12345678; // data for testing
   7 char *p= (char *)&a; // Pointer converted to character data
   8     
   9 if(*p == 0x78) // judge the order of the lowest byte
  10 return 1;
  11 return 0;
  12}
  13
  14 int main(int argc, char *argv[])
  15 {
  16 if(test_endian() == 1) // little endian
  17 {
  18 /* corresponding operation */
  19}
  20 else // big endian
  twenty one         {
  22 /* corresponding operation */
  twenty three         }
  24 return 0;
  25 }

Verify that the network byte order is big-endian

 1 #include 
   2 
   3 int main(int argc, char *argv[])
   4 {
   5 int a = 0x12345678;
   6 int b = htonl(a);
   7 char *p = (char *)&b;
   8 if((int)*p == 0x78)
   9 printf("little-endian\n");
  10 else if((int)(*p) == 0x12)
  11 printf("big-endian\n");
  12 else
  13 printf("unkonwn\n");
  14
  15 return 0;
  16 }

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/big-endian-little-endian-testing-the-native-data-storage-form_trb331617s-blog/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索