Quantcast
Channel: worksonmymachine
Viewing all articles
Browse latest Browse all 25

Bit reversing in C#, Part 1

$
0
0

So I recently had a discussion (read: interview) with an eminent member of Microsoft Ireland* where we discussed bit-reversing in C#. To be clear, I have no dealings with this level of code on a day-to-day basis. Like every rational software developer out there, I’m glad of the level of abstraction we currently enjoy. So I’m ashamed to say that it  was something of a challenge when he asked:

“Given that you know that one side of a stereo stream has the bits in each and every byte reversed, how do you represent the original stream accurately while preserving stereo integrity, i.e. using not more than one CPU cycle?”

So there I was, sitting in my ridiculously hot apartment (it hit 38 degrees Celsius around noon Friday) and thinking about this, and I drew a blank. Total, unmitigated, cruel, humiliating, mind bleach. All I could think of was (and I’m paraphrasing my mental processes but whatever)

1. I really want a cool beer my the lake right now.
2. How am I going to explain to my boss how late I’m gonna be back at the office?
3. What’s on the scrum board right now?
4. Not one of those horrible mass-produced ones either. A nice weissbier, perhaps, or a craft beer from the Amboss brewery.
5. I think I might move my salary account to another bank
6. Do I have any Ben And Jerry’s left?
7. I REALLY want a beer.
8. What was the problem again?

You get the picture.

So I came up with this;

private static byte swapBits(byte byteIn)
{
    var newBits = new[] { 0, 0, 0, 0, 0, 0, 0, 0 };
    var leastSignificant = 0;
    var wholeRemainder = (int)byteIn;
    for (int i = 0; i <= 7; i++)
    {
        int multiplier = 2;
        leastSignificant = wholeRemainder % multiplier;
        wholeRemainder = wholeRemainder / 2;
        newBits[7 - i] = leastSignificant;
    }
    int newByteValue = 0;
    int newMultiplier = 1;
    for (int i = 0; i <= 7; i++)
    {
        newByteValue += newBits[i] * newMultiplier;
        newMultiplier *= 2;
    }
    return (byte)newByteValue;
}

Meh.

This is serously gash. For starters, it’s possibly the most brute-force method of reversing bits in a byte. it’s dreadfully slow, a simple analysis would see that this is going to be in the order of 200-300 CPU cycles per function call.

A day or two later, after nursing my wounded ego with the aforementioned Ben & Jerry’s, I decided to look to the positive, and see if, with a bit of help from that newfangled Goggley doodad my kids keep talking about, I couldn’t come up with a better solution.

All to come in Part 2. For now, it’s back to B & J.

* needless to say, I failed the interview


Filed under: Uncategorized Tagged: bits, c#, lowlevel

Viewing all articles
Browse latest Browse all 25

Trending Articles