操作系统字节顺序表示

来源:互联网 发布:北京软件开发学校 编辑:程序博客网 时间:2024/06/04 19:50

假设变量x的类型是int,位于地址ox100处,它的十六进制数值为 ox01234567。地址范围为ox100~ox103的字节顺序依赖于机器的类型:

大端法:

ox100 ox101 ox 102 ox103

- - - - - - - - - - - - – — - - -

01 23 45 67

小端法:

ox100 ox101 ox 102 ox103

- - - - - - - - - - - - – — - - -

67 45 23 01

下面代码用于测试整数字节存储顺序。#include<stdio.h>#include<iostream>typedef unsigned char *byte_pointer; //声明指针类型void show_bytes(byte_pointer start, size_t len) //打印出每个以十六进制表示的字节{    size_t i;    for (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)ival;    int *pval = &ival;    show_int(ival);    show_float(fval);    show_pointer(pval);}int main(){    test_show_bytes(12345);    system("pause");}
运行结果:3930000000e44046c4f86f00

布尔代数简介:

~ 、&、|、^ 分别表示逻辑 运算 NOT 、AND 、OR 、EXCLUSIVE-OR(异或 即p或者q为真但不可同时为真)

我们可以将上述4个布尔运算符扩展到位向量的运算。

位向量就是由固定长度为w,由0和1组成的串。位向量的运算可以对应每个元素之间的运算。
下面利用逻辑运算实现交换函数。

#include<iostream>using namespace std;void inplace_swap(int *x, int *y){    *y = *x^*y;  //利用 a^a=0的性质来交换    *x = *x^*y;    *y = *x^*y;}int main(){    int m = 4;    int n = 5;    int *p1 = &m;    int *p2 = &n;    cout << *p1 << ' ' << *p2;    cout << endl;    inplace_swap(p1, p2);    cout << *p1 << ' ' << *p2;    system("pause") ;}4 55 4
原创粉丝点击