views:

107

answers:

4

Simple question:

How do i tell which bits in the byte are set to 0 and which are set to 1

for example:

//That code would obviously wont work, but how do i make something similar that would work?
byte myByte = 0X32;

foreach(bool bit in myByte)
{
  Console.WriteLine(bit);
}


//Part 2 revert
bool[] bits = new bool[8];
bits[0] = 0
bits[1] = 0
bits[2] = 0
bits[3] = 0
bits[4] = 0
bits[5] = 1
bits[6] = 0
bits[7] = 0

byte newByte = (byte)bits;

The entier internet is full of examples, but i just cant figure out

A: 

You can AND them. If the 1 bit is set in both numbers it will remain set. I'm not sure exactly what that sample is after, but AND'ing a bit with 1 will give you a true(1) or false(0).

0010 & 1010 = 0010

Ed Swangren
A: 

If all you want is an algorithm look here.

dirkgently
+1  A: 

BitArray class will be the simplest (though not necessarily the fastest) way possible.

Anton Gogolev
Hi, i'm trying to use this class, for example:byte myByte = 0X32;BitArray byt = new BitArray(myByte);foreach (bool bit in byt){ Console.WriteLine(bit.ToString());} but then im getting 32 0's instead of 8. im doing something wrong, just no idea what.
+5  A: 

You wanna use bit operations

k = bits = 0;
for (i = 1; i < 256; i <<= 1)
  bool[k++] = (bits & i) != 0;


k = bits = 0;
for (i = 1; i < 256; i <<= 1)
  if (bool[k++]) bits |= i;
Scott Evernden