Add a brick to the Establishment of Chinese knowledge base — The great Hu of Science and Technology

Problem description

C# byte order issues have recently been noticed. In the case of closed-loop development within a language, it is often not easy to notice the existence of byte order problems. There is no digital transmission conversion involved, and it is not easy to notice the existence of byte order problems.

Then C language, Linux running environment and Java were mixed together in the project design, and the Endian began to come into view, so I knew Big Endian and Little Endian.

The big-endian byte order is the same as our normal programming for the hexadecimal representation of numbers, with the higher order on the left and the lower order on the right. That’s how I understand it so I can remember it quickly.

@xiang knows the summary of common system and programming language endianness:

  • Windos(x86,x64) and Linux(x86,x64) are both Little Endian operating systems
  • On ARM, everything I’ve seen is Little Endian.
  • The order in which a C/C++ program is stored depends on the CPU on which it is compiled.
  • JAVA programs are the only ones that store data in a Big Endian way.
  • All network protocols also use the Big Endian way to transmit data. So we sometimes refer to the Big Endian approach as network byte order.

The sample code

#region Now we convert a float to byte[]

Console.WriteLine("Now we convert a float to byte[]:");
var z = 120.5 f;
Console.WriteLine($" float:{z}");

Console.WriteLine("BitConverter.getBytes () defaults to a small enjoined byte ordinal :");
var cc = BitConverter.GetBytes(z);
Console.WriteLine(BitConverter.ToString(cc));

Console.WriteLine("Array.reverse () reverses to the transport big-endeb :");
Array.Reverse(cc); // Reverse the array to the big endian.
Console.WriteLine(BitConverter.ToString(cc));

Console.WriteLine("Array.reverse () restores the little endian order recognized by C# :");
Array.Reverse(cc); // Restore to the little endian byte order
Console.WriteLine(BitConverter.ToString(cc));

Console.WriteLine("And we convert the byte[] to float:");
Console.WriteLine("Restore the numbers :" + BitConverter.ToSingle(cc, 0));

#endregion
Copy the code

Running result:

Refer to the article

  1. [C#] Big Endian and Little Endian
  2. Byte order processing in c# communication
  3. # C# float = Byte[