Working with bits in file headers

V

VanBurg

Hallo!

I have to do the following tasks:

1) I need to read first 4 bytes from file
2) Get all 32 bits for editing
3) Change some bits and save its back to file

For now i have to understand how to do only this:

FileStream fs = File.OpenRead (fileName);
fs.Read (this.HeaderBytes, 0, 4);
this.HeaderBits = new BitArray (this.HeaderBytes);

But bitarray will have (absolutely right) indexes, but i cannot do the following:

this.HeaderBits[8] = true;

'couse it will not change a byte at position 8 from left
XXXX XXXX [X]XXX XXXX
it will change
XXXX XXXX XXXX XXX[X]

Please give me easy and elegant way to manage bits< for example it may work like this:

Header.SetBit (byte pos, bool value);
Header.Save ();

Many thanks!
 
J

Jon Skeet [C# MVP]

VanBurg said:
I have to do the following tasks:

1) I need to read first 4 bytes from file
2) Get all 32 bits for editing
3) Change some bits and save its back to file

For now i have to understand how to do only this:

FileStream fs = File.OpenRead (fileName);
fs.Read (this.HeaderBytes, 0, 4);

You should check that the returned value here is 4.
this.HeaderBits = new BitArray (this.HeaderBytes);

There's no need to use a BitArray - just use normal bit arithmetic. For
instance, to set bit 8 (counting from the right):

HeaderBytes[3] |= 1;

To set bit 9, use

HeaderBytes[3] |= 2;

etc.
 
S

Soeren S. Joergensen

Hi,

Depending on the complexity of your operations you could use bit-shifting
and bit-assigment operator

Say you got an uint : 11111111 00000000 11111111 00000000 = 4278255360 and
want to flip bit 3 (right to left) in all four bytes your could:

uint myuint = 4278255360;
byte[] bs = new bs[4];

bs[0] = (byte)((myuint & 0xFF000000) >> 24); // Copy first 8 bits down
bs[1] = (byte)((myuint & 0x00FF0000) >> 16); // Copy second 8 bits down
bs[2] = (byte)((myuint & 0x0000FF00) >> 8); // Copy third 8 bits down
bs[3] = (byte)(myuint & 0x000000FF);

for(int i = 0; i < bs.Length; i++)
{
bs ^= 0x04; // Change third bit
}

myuint = (bs[0] << 24) + (bs[1] << 16) + (bs[2] << 8) + bs[3]; // Put myuint
back together

myuint = 4211407620 = 11111011 00000100 11111011 00000100

Above code is written out of the head to keyboard (no testing has been made)

Kr.
Soren
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top