RE: Need Help getting values from bits.
- From: KH <KH@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 28 Nov 2006 20:57:01 -0800
Hey Pete,
You probably need to use bitmasking - in the C languages the bitwise
operators & (AND), | (OR), ~ (NOT), and ^ (XOR). See C# docs and
http://en.wikipedia.org/wiki/Bitwise_operators
If you have only 3 variables I'd be inclined to declare 3 boolean variables
and set them by masking the appropriate byte (untested):
byte[] bytes = { 1, 2 };
bool a = (bytes[0] & 0xFF) == 1; // TRUE because the first bit of bytes[0]
is ON
bool b = (bytes[0] & 0xFF) == 2; // FALSE because the 2nd bit of bytes[0] is
OFF
bool c = (bytes[1] & 0xFF) == 2; // TRUE because the 2nd bit of bytes[1] is ON
// Use the bool variables now...
If there's a bunch of significant bytes you might just test each one as you
go...
if ((bytes[1] & 0xFF) == 2) // do something
.... or maybe each byte represents only one condition? ...
if ((bytes[0] & 0xFF) > 0) // do something
HTH ... - KH
"Pete" wrote:
Hi,.
First, thanks for any time you spend helping me, I'm at a loss. I'm not
bit-savvy, so I apologize if this is extremely simple, or I am going about
this the wrong way.
I am trying to take a byte array and extract some information from that
array, and convert it back to a hex value. For instance, I have a byte[]
that I populated from a BinaryReader of a file. Now, lets say it's 4 bytes
in length. Out of those 32 bits I need to get the hex value of certain
bits, like 3 bits starting at offset 10. The header information I am
reading from the file is not byte aligned, so most of the values I am going
to be looking at will be two to eight bits spanning different bytes.
I've been able to move the data into a BitArray, but from that point I'm at
a loss as to what to do with the BitArray, or if that is even the right
direction to go.
Any help in the right direction would be greatly appreciated.
Thank you!
- Follow-Ups:
- Re: Need Help getting values from bits.
- From: Marc Gravell
- Re: Need Help getting values from bits.
- References:
- Need Help getting values from bits.
- From: Pete
- Need Help getting values from bits.
- Prev by Date: Re: DataGridView layout control in windows forms
- Next by Date: Code Snippet Insertion - Where Documented
- Previous by thread: Need Help getting values from bits.
- Next by thread: Re: Need Help getting values from bits.
- Index(es):
Relevant Pages
|