This method reverse the bits of a byte:
// Reverses bits in a byte public static byte Reverse(byte inByte) { byte result = 0x00; for (byte mask = 0x80; Convert.ToInt32(mask) > 0; mask >>= 1) { // shift right current result result = (byte) (result >> 1); // tempbyte = 1 if there is a 1 in the current position var tempbyte = (byte)(inByte & mask); if (tempbyte != 0x00) { // Insert a 1 in the left result = (byte) (result | 0x80); } } return (result); }
A possible improvement could be to use this method to initialize the application to creating a table with all bytes and its inverted value.
Paying a slower initialization and more memory consumption all the conversions at runtime would be much faster.
Hello, mybe I missed something, but why do not use this:
public static byte Reverse(byte inByte)
{
return (byte)~inByte;
}
…or even better do it in extension form:
public static class ByteExtension
{
public static byte Reverse(this byte inByte)
{
return (byte)~inByte;
}
}
then you will be able to use it in this way:
byte b = 0xAA;
byte inerted = b.Invert();
LikeLike
Hello, you are right.
That operator does the job. The idea of this old post was to do it in an “academic” way.
Thank you for your comment.
LikeLike