位結構體+大小端模式

來源:互聯網
上載者:User

 

位結構是一種特殊的結構, 在需按位訪問一個位元組或字的多個位時, 位結構比按位元運算符更加方便
 
位結構定義的一般形式為:
struct  位結構名{
資料類型 [變數名]: 整型常數;
資料類型 [變數名]: 整型常數;
}位結構變數;

資料類型必須是整型(int char short)

例如:定義一個位結構
struct test{
char a: 8;
char b: 4;
char c: 3;
char d: 1;
}ch;
printf("%d\n",sizeof(struct test));

a:佔用低位元組的0~7共8位
b:佔用高位元組的0~3位
c:佔用高位元組的4~6位
d:佔用高位元組的第7位

輸出多少?
(8+4+3+1)/8=2

 

struct info{
char name[8];
int age;
float pay;
unsigned char state: 1;
unsigned char pay: 1;
}workers;

sizeof(workers)=20
8+4+4+4(位結構體的大小應為最大成員<int>的整數倍)

位結構體成員叫位域,注意事項:
1. 一個位域必須儲存在同一個位元組中,不能跨兩個位元組
   struct bs
  {
  unsigned a:4
  unsigned :0 /*空域*/
  unsigned b:4 /*從下一單元開始存放*/
  unsigned c:4
  }
  在這個位域定義中,a占第一位元組的4位,後4位填0表示不使用,b從第二位元組開始,佔用4位,c佔用4位。
2.位域不允許越過定義它的資料類型
3.位域可以無位網域名稱,這時它只用來作填充或調整位置。無名的位域是不能使用的
struct k
  {
  int a:1
  int :2 /*該2位不能使用*/
  int b:3
  int c:2
  };

 

#include<stdio.h>
void main()
{
 union
 {
 struct student
 {
   unsigned char s1:1;
   unsigned char s2:3;
 }x;
 unsigned char c;
 }v;
 v.c=0;
 v.x.s1=0;
 v.x.s2=4;
printf("%d\n",v.c);
printf("%d\n",sizeof(struct student)); 
}
8(小端模式)
1

64(大端模式)
1
本題小結:
 像intel的CPU是小端模式:
   若左邊是低位,右邊是高位(不定),
   如上面的例子中s1(0)比s2(100)先執行,先執行的一定是放低位,但s2的要反過來寫(即001),在記憶體中表現為0 001,因為電腦是以位元組為單位的,位元組佔八位,即後面四位補零,得:0001 0000,再有,小端模式是從高位讀到低位的,即從右往左讀,結果就是8;
 像摩托羅拉的CPU是大端模式:
    若左邊是低位,右邊為高位(自定),
   如上面的例子中s1(0)比s2(100)先執行,先執行的一定是放低位,s2的不要反過來寫(即100),在記憶體中表現為0 100,因為電腦是以位元組為單位的,位元組佔八位,即後面四位補零,得:0100 0000,再有,大端模式是從低位讀到高位的,即從左往右讀,結果就是64;

 

#include<stdio.h>
void main()
{
 union
 {
 struct student
 {
   unsigned char s1:1;
   unsigned char s2:2;
   unsigned char s3:2;
 }x;
 unsigned char c;
 }v;
 v.c=0;
 v.x.s1=0;
 v.x.s3=2;
printf("%d\n",v.c);
printf("%d\n",sizeof(struct student)); 
}

16(大小端都是)
1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.