Binary file format: why did the system read all the 4 bytes and displayed the value correctly as 25736483

StackOverflow https://stackoverflow.com/questions/23160948

  •  05-07-2023
  •  | 
  •  

Using a c# program BinaryWriter class I am writing 2 words in a file

bw.write(i);
bw.write(s);

where i is an integer with value 25736483. and s is a string with value I am happy

I am reading the file again and outputting the value to a textbox.text

iN = br.ReadInt32();
newS = br.ReadString();

this.textBox1.Text = i.ToString() + newS;

The integer will be stored in 4 bytes and the string in another 11 bytes. When we read the ReadInt32 how did the system know that it has to spawn 4 bytes and not only 1 byte. Why did the system read all the 4 bytes and displayed the value correctly as 25736483?

有帮助吗?

解决方案

You told it to read an Int32 with ReadInt32, and an Int32 is 4 bytes (32 bits). So you said "Read a four byte (32-bit) integer", and it did exactly what you told it to do.

The same thing happened when you used bw.write(i); - as you said, i is an integer, and you told it to write an integer. Since the default integer is 4 bytes (32 bits) on your platform, it wrote 4 bytes.

其他提示

Integers are 32-bits on your platform. So when you passed an integer to write, you got an overload that writes 4 bytes. The ReadInt32 function knows to read four bytes because 32 bits is four bytes, so that's what it always does.

The Write method has an overload for each variable type that it knows how to write. This overload knows exactly how many bytes it takes to store the value in the stream. You can see every specific overload here.

When you read data you call the correct version of .Read for the data type you are trying to read, which is also specifically coded to know how many bytes are in that type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top