当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++基础入门教程

高位优先和低位优先

    查看内存布局。

 

    可能比较绕口,那就是最低的地址存放高位字节,称为高位优先,最低的地址存放低位字节,成为低位优先

    详细的内存察看如下:

 

代码:
#include <stdio.h> 
struct ss{
unsigned int i1:1;
unsigned int i2:1;
unsigned int i3:1;
unsigned int i4:1;
unsigned int i5:1;
unsigned int i6:1;
unsigned int i7:1;
unsigned int i8:1;
unsigned int j1:1;
unsigned int j2:1;
unsigned int j3:1;
unsigned int j4:1;
unsigned int j5:1;
unsigned int j6:1;
unsigned int j7:1;
unsigned int j8:1;
unsigned int k1:1;
unsigned int k2:1;
unsigned int k3:1;
unsigned int k4:1;
unsigned int k5:1;
unsigned int k6:1;
unsigned int k7:1;
unsigned int k8:1;
unsigned int l1:1;
unsigned int l2:1;
unsigned int l3:1;
unsigned int l4:1;
unsigned int l5:1;
unsigned int l6:1;
unsigned int l7:1;
unsigned int l8:1;
};
int main()
{
struct ss s;
int j=1025;
memcpy(&s,&j,4);
printf("%d\n",sizeof(struct ss));
printf("%d%d%d%d%d%d%d%d\n",s.i1,s.i2,s.i3,s.i4,s.i5,s.i6,s.i7,s.i8);
printf("%d%d%d%d%d%d%d%d\n",s.j1,s.j2,s.j3,s.j4,s.j5,s.j6,s.j7,s.j8);
printf("%d%d%d%d%d%d%d%d\n",s.k1,s.k2,s.k3,s.k4,s.k5,s.k6,s.k7,s.k8);
printf("%d%d%d%d%d%d%d%d\n",s.l1,s.l2,s.l3,s.l4,s.l5,s.l6,s.l7,s.l8);
return 0;
}


    开始说说高位优先和低位优先,我们看如下代码:
    int i=10;
    那么i在内存中的布局如何哪?
    假设内存是从低--->高增长的
    在低位优先的硬件里面,内存布局如下:
    00001010 00000000 00000000 00000000
    而在高位优先的内存中:
    00000000 00000000 00000000 00001010
    这就是我们经常听说的高位优先,低位优先。
    那么我们需要注意什么冬冬勒?
    看下面一个程序:
    #include <stdio.h>
        main()
        {
            int a=10;
            short b;
            memcpy(&b,&a,2);
            printf("%d\n",b);
        }
    如果你输出结果为:10,恭喜你,你的内存存储是低位优先,
    如果结果为:0呢?恭喜你,你的内存存储是高位优先。
    btw:在处理器中总是高位优先。

相关内容
赞助商链接