|
Post by J. Cathcart on Apr 12, 2003 9:45:28 GMT -5
Hi I wanna decompose a number read from file to bits (o,1). Also I wanna know if there is something similar 2 union in C++
|
|
|
Post by Çòùrtnèy_Ч on Apr 13, 2003 8:10:52 GMT -5
There's a class called (I believe) BinaryReader that does exactly what you want... It takes a Stream in the constructor and then you can read bits out in any form you like... I don't have the documentation in front of me right now.. but it works like this:
Stream s = File.OpenRead(@"path/to/file.ext"); BinaryReader reader = new BinaryReader(s);
// Now you can read bits out of the stream byte b; b = reader.ReadByte(); // read a byte out
int i; i = reader.ReadInt(); // read 4 bytes out
Sincerely CourtneyDS
|
|
|
Post by J. Cathcart on Apr 13, 2003 22:51:02 GMT -5
Thank u very much, but the problem that I can read bytes wiz that reader but I wanna read bits tha compose this bytes ?, Do u have any idea about that?
|
|
|
Post by Çòùrtnèy_Ч on Apr 14, 2003 7:08:15 GMT -5
Once you have the byte.. you're pretty well set... You can just add the byte with a mask to get the value of a specific bit... For example.. say you want to know the value of the right-most bit of the byte...
Read byte: 11001010 Apply mask:00000001
When you add those two things.. you'll wind up with a 0 if the bit in question was a 0.. and a 1 otherwise... So your code might look like this:
// Reader is a BinaryReader byte b = reader.ReadByte();
// Is the lowest-bit a 1? if (b & 0x01 == 0x01) { // lowest bit was set
}
^^ If this doesn't make sense to you.. I recommend reading a bit on working with binary operators ...:
Sincerely CourtneyDS
|
|
|
Post by J. Cathcart on Apr 16, 2003 16:54:25 GMT -5
Thank you very much Courtney, It works! It works!
|
|