Reading and writing binary file, file unexpectedly large?

This is a continuation of my last question.

I’m trying to write to a binary file in the editor, then read from the file at runtime. The method I’m using works, but it’s creating a 16mb file, while I was expecting about a 2mb file. What am I doing wrong? This obviously isn’t writing just 0’s and 1’s for the bool values, but char bytes instead. And I thought this stepped bit by bit through the file or did I misunderstand this page [msdn.microsoft.com][1]

	// in editor this is called to create the file
	private void WriteBinaryFile()
	{
		string filePath = @"C:\PathToProject\Assets\Resources\";
		
		using(BinaryWriter writer = new BinaryWriter(File.Open(filePath + "file.txt", FileMode.Create)))
		{
			for(int i = 0; i < 16777215; i++)
			{
				writer.Write(largeBoolArray*);*
  •  	}*
    
  •  	writer.Close();*
    
  •  }*
    
  • }*

  • // at runtime this is called to read the file*

  • private void ReadBinaryFile()*

  • {*

  •  if(File.Exists("Assets/Resources/file.txt"))*
    
  •  {*
    
  •  	using(BinaryReader reader = new BinaryReader(File.Open("Assets/Resources/file.txt", FileMode.Open)))*
    
  •  	{*
    
  •  		for(int i = 0; i < 16777215; i++)*
    
  •  		{*
    

_ largeBoolArray = reader.ReadBoolean();_
* }*
* reader.Close();*
* }*
* }*
* else*
* Debug.LogError(“Binary file does not exist in ReadBinaryFile()!”);*
* }*
_*[1]: Microsoft Learn: Build skills that open doors in your career

The smallest addressable size is 1 byte so when you save a bool it takes up all the space of the byte. To make your file smaller you should pack multiple bools into a type that takes up at least one byte using bitwise operators. Then when you load the array you should similarly unpack the data. Here is something to get you started.

private void WriteBinaryFile(string filePath) {    
    using(BinaryWriter writer=new BinaryWriter(File.Open(filePath+"file.txt", FileMode.Create))) {
        int toSave=0;
        int x=0;
        for(int i=0; i<16777215; i++) {
            if(largeBoolArray*) {*

toSave=toSave|(1<<x);
}
x++;

if(32<=x) {
writer.Write(toSave);
x=0;
toSave=0;
}
}
writer.Close();
}

}

private void ReadBinaryFile() {
if(File.Exists(“Assets/Resources/file.txt”)) {
using(BinaryReader reader=new BinaryReader(File.Open(“Assets/Resources/file.txt”, FileMode.Open))) {
int toLoad;
for(int i=0; i<16777215;) {
toLoad=reader.ReadInt32();

for(int x=0; x<32 && i<16777215; ){
largeBoolArray*=((toLoad>>x)&1)==1;*
x++;
i++;
}
}
reader.Close();
}
}
else
Debug.LogError(“Binary file does not exist in ReadBinaryFile()!”);
}