best way to reverse bit order of data type ?

L

Laszlo Szijarto

In C#, wha't the best way to reveser the bit order of a data type and then
convert it back to that datatype?

So, take a byte, reverse bits, convert it back to a byte. I tried to get a
BitArray and then call Array.Reverse(), but how to convert back to byte?

How about flipping an odd number of bits, say a group of 4 bits, then
converting the 4 bits back to an int equivalent?

Thanks you in advance for your help,
Laszlo
 
N

Nicholas Paldino [.NET/C# MVP]

Laszlo,

You can use the CopyTo method to copy the bits back into an array of
byte, bool, and int, if you wish. However, for other types, this will not
work. For those types, you might have to use the BitArray class to swap the
bits around, and then get a byte array representing the flipped bits. Once
you have that, you can use the BitConverter class to convert the byte array
to whatever type you wish.

Hope this helps.
 
K

Konrad L. M. Rudolph

Laszlo said:
In C#, wha't the best way to reveser the bit order of a data type and then
convert it back to that datatype?

So, take a byte, reverse bits, convert it back to a byte. I tried to get a
BitArray and then call Array.Reverse(), but how to convert back to byte?

Why the effort? There's much simpler:

\\\
byte ByteVar = 125;
ByteVar = (byte)(~(int)ByteVar);

MessageBox.Show(this, ByteVar.ToString());
///
 
N

Nicholas Paldino [.NET/C# MVP]

Konrad,

This will get the inverse of the bits in the byte, not a byte with the
bits in reverse order.
 

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