联合体在嵌入式开发中的妙用

1. 检测当前处理器是大小端模式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef union div
{
   unsigned int  all;      // all中存放要进行分离高低字节的数据
   unsigned char ch[4];    // char占一个字节,所以all与数组ch占的字节数相同
}DIVIDER;

int main()
{
  DIVIDER divider;
  divider.all = 0x11223344;
  
  if(0x44 == divider.ch[0])
  {
     printf("little endian \n");
  }
  else
  {
      printf("big endian \n");
  }

  return 0;
}

2. 按字节分离一个WORD或者DWORD数据

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef union div
{
   unsigned int  all;      // all中存放要进行分离高低字节的数据
   unsigned char ch[4];    // char占一个字节,所以all与数组ch占的字节数相同
}DIVIDER;

int main()
{
  int i = 0;
  DIVIDER divider;
  unsigned char DIV[4];

  divider.all = 0x11223344;

  /* 下面通过访问divider中数组ch的数据来取出高低字节的数据 */
  for(i = 0; i < 4; i++)
  {
      DIV[i] = divider.ch[i];
      printf("DIV[%d] =0x%x \n",i,DIV[i]);
  }
    return 0;
}

3.硬件寄存器封装

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef union ISP_BLC_REG
{
  unsigned int  all;
  struct
  {
  unsigned int bit0:2;
  unsigned int bit1:2;
  unsigned int bit2:2;
  unsigned int bit3:2;
  unsigned int bit4:2;
  unsigned int bit5:2;
  unsigned int bit6:2;
  unsigned int bit7:2;
  unsigned int bit8:2;
  unsigned int bit9:2;
  unsigned int bit10:2;
  unsigned int bit11:2;
  unsigned int bit12:2;
  unsigned int bit13:2;
  unsigned int bit14:2;
  unsigned int bit15:2;
  };

}ISP_BLC_REG;

typedef union ISP_AWB_REG
{
  unsigned int  all;
  struct
  {
  unsigned int bit0:2;
  unsigned int bit1:2;
  unsigned int bit2:2;
  unsigned int bit3:2;
  unsigned int bit4:2;
  unsigned int bit5:2;
  unsigned int bit6:2;
  unsigned int bit7:2;
  unsigned int bit8:2;
  unsigned int bit9:2;
  unsigned int bit10:2;
  unsigned int bit11:2;
  unsigned int bit12:2;
  unsigned int bit13:2;
  unsigned int bit14:2;
  unsigned int bit15:2;
  };
};

}ISP_AWB_REG;

typedef struct isp_reg
{
  volatile   ISP_AWB_REG     isp_blc;
  unsigned   int             rev[2];
  volatile   ISP_BLC_REG     isp_awb;
}ISP_REG_S;


int main()
{
  ISP_REG_S *gst_isp = NULL;

  gst_isp = (ISP_REG_S *)malloc(sizeof(ISP_REG_S));
  if(NULL == gst_isp)
  {
    printf("gst_isp malloc is fail!\n");
    return -1;
  }

  gst_isp->isp_blc.all = 0x11111111;

  printf("gst_isp  =0x%x\n",gst_isp);
  printf("gst_isp->isp_blc  =0x%x\n",&gst_isp->isp_blc);
  printf("gst_isp->isp_awb  =0x%x\n",&gst_isp->isp_awb);

  printf("gst_isp->isp_blc.bit0  =0x%x\n",gst_isp->isp_blc.bit0);

  gst_isp->isp_blc.bit0 = 0x0;

  printf("gst_isp->isp_blc.bit0  =0x%x\n",gst_isp->isp_blc.bit0);

  if(gst_isp != NULL)
  {
    free(gst_isp);
  }
  
  return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值