大头小头字节序

何为小头序?

#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
    FILE*file = fopen("haha.txt", "wb");
    short x = 256;
    fwrite(&x, sizeof(x), 1, file);
    fclose(file);
    file = fopen("haha.txt", "rb");
    char c;
    fread(&c, sizeof(c), 1, file);
    cout << (int)c << endl;
    fread(&c, sizeof(c), 1, file);
    cout << (int)c << endl;
    return 0;
}

如上代码输出为0,1.我往文件中写了一个short类型的256,低位在低地址,高位在高地址,这就是小头字节序。即小头在前面。
反之,如果高位在低地址,低位在高地址,则为大头字节序。

大头序的输入

    file = fopen("haha.txt", "rb");
    char c;
    int n=0;
    for(int i=0;i<4;i++){
        fread(&c,sizeof(c),1,file);
        n=(n<<8)|c;
    }

谁用大头序?

java平台二进制读写一律采用大头字节序,网络上数据传输也都采用大头字节序。

c++不跨平台,所以它的大小头依赖于系统架构,intel系列通常是小头字节序,arm体系通常是大头序列。

网络上通常采用大头字节序,所以大头字节序又叫网络字节序。

intel占据大量PC,都采用小头字节序,所以小头字节序又叫主机字节序。

public class Main {
    public static void main(String[] args) throws IOException {
        DataOutputStream o = new DataOutputStream(new FileOutputStream("haha.txt"));
        o.writeInt(12332);
        o.close();
        DataInputStream i = new DataInputStream(new FileInputStream("haha.txt"));
        int n = 0;
        for (int j = 0; j < 4; j++) {
            n = (n << 8) | i.read();
        }
        System.out.println(n);//程序输出12332
    }
}
原文地址:https://www.cnblogs.com/weiyinfu/p/5217012.html