little-endian and big-endian

博客介绍了计算机架构中大小端的概念,大端是从左到右编号字节,小端是从右到左编号字节。还给出C#示例,有两个txt文件采用不同编码方式,分别用二进制和StreamReader读取内容,得出UCS - 2 Little Endian编码文件以FFFE开头,UCS - 2 Big Endian编码文件以FEFF开头的结论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Some computer architectures number bytes in a binary word from left to right, which is referred to as

big-endian

Other architectures number the bytes in a binary word from right to left, which is referred to as little-endian.

Using big-endian and little-endian methods, the number 0x12345678 would be stored as shown in the following table.

 

 

Byte order

Byte 0

Byte 1

Byte 2

Byte 3

Big-endian

0x12

0x34

0x56

0x78

Little-endian

0x78

0x56

0x34

0x12

例子:
下面C# code中有2个txt文件:LittleEndian.txt和BigEndian.txt,他们包含相同的文本内容:都是aa,但不同的编码方式,分别是UCS-2 Little Endian 和UCS-2 Big Endian.

示例中先分别用二进制的方式读出文件中的内容;再用StreamReader读出文件的内容

 static void Main(string[] args)
        {
            byte[] leBytes = ReadAsBinary(".\\LittleEndian.txt");
            Console.WriteLine("Little Endian:");
            PrintByteArray(leBytes);
            Console.WriteLine();

            byte[] bigBytes = ReadAsBinary(".\\BigEndian.txt");
            Console.WriteLine("Big Endian:");
            PrintByteArray(bigBytes);
            Console.WriteLine();

            byte[] srByes;
            using (StreamReader reader = new StreamReader(".\\LittleEndian.txt", true))
            {
                srByes = Encoding.Unicode.GetBytes(reader.ReadToEnd());
            }
            Console.WriteLine("StreamReader Little Endian:");
            PrintByteArray(srByes);
            Console.WriteLine();
}

        private static byte[] ReadAsBinary(string path)
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
            BinaryReader breader = new BinaryReader(fs);
            byte[] bytes = breader.ReadBytes(6);
            return bytes;
        }

输出:

结论:

UCS-2 Little Endian编码的文件,其内容以FFFE开头;

UCS-2 Big Endian编码的文件,其内容以FEFF开头;

 

转载于:https://www.cnblogs.com/jenneyblog/archive/2010/06/29/1767330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值