Reputation:
How can i write all bits of a file using c#? For example writing 0 to all bits
Please provide me with a sample
Upvotes: 0
Views: 1112
Reputation: 65426
When you say write all bits to a file I'll assume you mean bits as in nyble, bit, byte. That's just writing an integer to a file. You can't have a 4 bit file as far as I know so the smallest denomination will be a byte.
You probably don't want to be responsible for serializing yourself, so your easiest option would be to use the BinaryReader and BinaryWriter classes, and then manipulate the bits inside your C#.
The BinaryWriter
class uses a 4 byte integer as minimum however. For example
writer.Write( 1 ); // 01
writer.Write( 10 ); // 0a
writer.Write( 100 ); // 64
writer.Write( 1000 ); // 3e8
writer.Write( 10000 ); // 2710
//writer.Write( 123456789 ); // 75BCD15
is written to file as
01 00 00 00 0a 00 00 00 64 00 00 00 e8 03 00 00 10 27 00 00 15 cd 5b 07
Upvotes: 0
Reputation: 116654
I'm not sure why you'd want to do this, but this will overwrite a file with data that is the same length but contains byte values of zero:
File.WriteAllBytes(filePath, new byte[new FileInfo(filePath).Length]);
Upvotes: 6
Reputation: 6390
Definitely has the foul stench of homework to it.
Hint - Think why someone might want to do this. Just deleting the file and replacing with a file of 0s of the correct length might not be what you're after.
Upvotes: 2
Reputation: 100567
Consider using the BinaryWriter
available in the .NET framework
using(BinaryWriter binWriter =
new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
binWriter.Write("Hello world");
}
Upvotes: 1
Reputation: 33348
Have a look at System.IO.FileInfo
; you'll need to open a writable stream for the file you're interested in and then write however many bytes (with value 0 in your example) to it as there are in the file already (which you can ascertain via FileInfo.Length
). Be sure to dispose of the stream once you're done with it – using
constructs are useful for this purpose.
Upvotes: 1
Reputation: 3126
read into a byte and then test against >= powers of 2 to get each of the bits in that byte
Upvotes: 0