c union

定义一个联合类型的一般形式为:  
union 联合名  
{  
成员表  
}; 


例如:  
union w

   int a; 
   char b; 
}; 
  联合定义之后,即可进行联合变量说明,被说明为w类型的变量,可以存放整型量a或存放字符数组b。 

二、联合变量的说明 

  联合变量的说明和结构变量的说明方式相同, 也有三种形式。即先定义,再说明;定义同时说明和直接说明。以w类型为例,说明如下:  
union w 

   int a; 
   char b; 
}; 
union w  c,d; 

或者可同时说明为:  
union w 
{  
int a; 
char b;  
}c,d; 


或直接说明为:  
union 
{  
int a; 
char b;  
}c,d 

 

   union中的成员变量,因为共享同一快内存区域,所以要么赋予整型值,要么赋予字符串,不能把两者同时赋予它。

   union存在的情形:我们常常使用几个变量,但其中只有一个变量在任意给定的时刻有有效值。

   另一种情形:程序处理许多不同类型数据,但是一次只能处理一种,要处理的类型在执行期间确定。

   再一种:要在不同的时间访问相同的数据,但在不同的情况下该数据的类型是不同的。

 判断cup是big_endian or little_endian

  1. #include<stdio.h>  
  2.   
  3. int checkCPU(){  
  4.     union  {  
  5.         int a;  
  6.         char b;  
  7.   
  8.         }c;  
  9.          c.a=1;  
  10.          return (c.b==1);  
  11.     }  
  12. int main(){  
  13.     int a =0 ;  
  14.     a=checkCPU();  
  15.     printf("%d",a);  
  16.     }  

 

 

  1. int checkCPU(){    
  2.     int i = 1;    
  3.     return *((char*)&i)==1 ? 1 : 0;    
  4. }  




 We've defined a word to mean 32 bits. This is the same as 4 bytes. Integers, single-precision floating point numbers, and MIPS instructions are all 32 bits long. How can we store these values into memory? After all, each memory address can store a single byte, not 4 bytes.

我们知道一个整型占4字节,32位,应该怎么在内存中存储呢,每个内存空间存储一个字节,不是4个

The answer is simple. We split the 32 bit quantity into 4 bytes. For example, suppose we have a 32 bit quantity, written as 90AB12CD16, which is hexadecimal. Since each hex digit is 4 bits, we need 8 hex digits to represent the 32 bit value.

答案是简单的,我们可以分成4个连续的内存区域,比如十六进制数 90AB12CD

So, the 4 bytes are: 90, AB, 12, CD where each byte requires 2 hex digits.

It turns out there are two ways to store this in memory

于是分为下面两个存储方式:

Big Endian

In big endian, you store the most significant byte in the smallest address. Here's how it would look:

AddressValue
100090
1001AB
100212
1003CD
Little Endian

In little endian, you store the least significant byte in the smallest address. Here's how it would look:

AddressValue
1000CD
100112
1002AB
100390

 LSB 最低有效位;least significant bit

 MSB最高有效位 most significant bit

变量类型所占的内存空间取决于所使用的编译器

操作系统的位数:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值