I want to write the numbers 1 and 2 (UInt32) to the file using BinaryWriter, then output all the bytes in turn to the console.

static void Main(string[] args) { FileStream fs = new FileStream(@"G:\out.dat", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write((UInt32) 1); bw.Write((UInt32) 2); bw.Close(); fs = new FileStream(@"G:\out.dat", FileMode.Open); BinaryReader br = new BinaryReader(fs); for (int i = 0; i < 8; i++) { byte b = br.ReadByte(); string byte_in_str = ByteToStr(b); Console.WriteLine(i + 1 + ". " + byte_in_str); } br.Close(); } static string ByteToStr(byte b) { string bin = ""; for (int i = 128; i > 0; i /= 2) if ((b & i) != 0) bin += "1"; else bin += "0"; return bin; } 

As a result, I have the following result: non-zero bits are in 1st and 5th place for each of the numbers, judging by the conclusion. In theory, the number '1' in the UInt32 representation has only the 32nd nonzero bit, that is, the first 3 bytes are uniquely zero. And here the first byte is non-zero, after which 3 zero passes go, which contradicts the previous statement. What don't I understand?

  • 32-bit or, more precisely, the 31st bit (Most Significant Bit) is used to sign a number - Vlad from Moscow
  • So how is the number '1' written to a file? Are all 4 bits written from right to left? That is, it is clear to me that the number is 00000000 00000000 00000000 00000001, but does the machine write it down from the last? - Exide
  • It seems that the lower bits of the number are located at lower addresses. - Vlad from Moscow
  • Is the younger one the next? If yes, then everything is clear - Exide
  • The number takes 4 bytes and is stored as, conditionally speaking, at address 0 — the high byte, at address 1 — the next byte, etc., and at address 3, the low byte. - Vlad from Moscow

1 answer 1

BinaryWriter uses a byte order called little endian. Low bytes are written to the stream first.

  • Thank you, that's all clear. - Exide
  • @Exide: Then put a green check mark on the left. - VladD