zoukankan      html  css  js  c++  java
  • union、struct对齐

    #include<stdio.h>
    
    static union
    {
        char c[4];
        unsigned long l;
    }endian_test = { {'l','?','?','b'} };
    
    #define ENDIANNESS ( (char)endian_test.l )
    
    
    union U{
        char s[9]; //size: 9
        int n;     //size: 4 
        double d;  //size: 8
    };             //size: 16

    union 的最小的size是所包含的所有类型的基本长度的最小公倍数才行
    struct S { char s[9]; //size: 9 int n; //size: 4 double d; //size: 8 }; //size: 24 int main() { printf( "sizeof int = [%ld] ", sizeof( int ) ); printf( "sizeof unsigned long = [%ld] ", sizeof(unsigned long ) ); printf( "sizeof double = [%ld] ", sizeof( double ) ); printf( "sizeof union U = [%ld] ", sizeof( union U ) ); printf( "sizeof struct S = [%ld] ", sizeof( struct S ) ); printf( "ENDIANESS = %c ", ENDIANNESS ); }

    Detect endianness at run-time

     1 #include <stdint.h>
     2 
     3 enum {
     4   ENDIAN_UNKNOWN,
     5   ENDIAN_BIG,
     6   ENDIAN_LITTLE,
     7   ENDIAN_BIG_WORD,   /* Middle-endian, Honeywell 316 style */
     8   ENDIAN_LITTLE_WORD /* Middle-endian, PDP-11 style */
     9 };
    10 
    11 int endianness(void)
    12 {
    13   union
    14   {
    15     uint32_t value;
    16     uint8_t data[sizeof(uint32_t)];
    17   } number;
    18 
    19   number.data[0] = 0x00;
    20   number.data[1] = 0x01;
    21   number.data[2] = 0x02;
    22   number.data[3] = 0x03;
    23 
    24   switch (number.value)
    25   {
    26   case UINT32_C(0x00010203): return ENDIAN_BIG;
    27   case UINT32_C(0x03020100): return ENDIAN_LITTLE;
    28   case UINT32_C(0x02030001): return ENDIAN_BIG_WORD;
    29   case UINT32_C(0x01000302): return ENDIAN_LITTLE_WORD;
    30   default:                   return ENDIAN_UNKNOWN;
    31   }
    32 }
  • 相关阅读:
    2014/11/25 函数
    2014/11/24 条件查询
    2、计算器
    1、winform数据库调用(基本方法)
    1、网页基础
    14、函数输出参数、递归
    13、C#简易版 推箱子游戏
    12、函数
    11、结构体、枚举
    10、特殊集合
  • 原文地址:https://www.cnblogs.com/merlindu/p/6561382.html
Copyright © 2011-2022 走看看