登录
    Technology changes quickly but people's minds change slowly.

计算机操作系统-寻址和字节顺序

技术宅 破玉 1283次浏览 0个评论

        基本上在所有的机器上,多字节对象都被存储为连续的字节序列,对象的地址为所使用字节中最小的地址。假设一个int 变量x的地址为0x100,那么(假设int 为32位表示)x的4个字节被存储在内存 0x100、0x101、0x102、0x103 的位置。在某些机器中选择在内存中按照从低有效字节到高有效字节的顺序存储对象,而另一些机器按照从最高有效字节从最低有效字节存储。最低有效字节在前的方式称为小端法,最高有效字节在前称为大端法。
        假设变量x的类型为 int ,位于0x100 处,它的十六进制为 0x01234567 地址范围 0x100~0x103 的字节顺序按照大小端法 为如下表示:

注意: 在 字 0x01234567 中,高位字节16进制为 0x01 ,低位字节16进制为0x67。
         大多数的intel兼容机都只用小端模式,一般的在linux 和windows 都是小端法。
检验字节序可使用如下 c语言代码,linux 下可以执行:

 gcc -o show_bytes show_bytes.c
./show_bytes

打印字节序代码如下:

#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start,size_t len){
    size_t i;
    for (int i = 0; i <len ; i++) {
        printf("%.2x",start[i]);
    }
    printf("\n");
}

void show_int(int x){
    show_bytes((byte_pointer) &x,sizeof(int));
}

void show_float(float x){
    show_bytes((byte_pointer) &x,sizeof(float));
}

void show_pointer(void *x){
    show_bytes((byte_pointer) &x,sizeof(void *));
}

void test_show_bytes(int val){
    int ival=val;
    float fval=(float) val;
    int *pval=&ival;
    show_int(ival);
    show_float(fval);
    show_pointer(pval);
}

int main(){
    test_show_bytes(12345);
    return 0;
}

华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明计算机操作系统-寻址和字节顺序
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址