5

I don't know what to call this, which makes googling harder.

I have an integer, say 3, and want to convert it to 11100000, that is, a byte with the value of the integers number of bits set, from the most significantly bit.

I guess it could be done with:

byte result = 0;
for(int i = 8; i > 8 - 3; i--)
    result += 2 ^ i;

but is there anything faster / more nice or, preferably, standard library included in .net?

4
  • What if your integer is greater than 8? Commented Nov 27, 2011 at 17:47
  • 6
    Just a small point ^ is an Exclusive Or in C# not the Power operator. Commented Nov 27, 2011 at 17:51
  • @Martin Haha thanks, took me a few seconds just now to realize. Easy to forget sometimes, if you also happen to write equations for a paper while programming. Commented Nov 27, 2011 at 18:22
  • @Max, I only know this because I've made the same mistake 100s of times myself. Commented Dec 1, 2011 at 11:08

2 Answers 2

11
int n = 3; // 0..8 
int mask = 0xFF00;
byte result  = (byte) (mask >> n);
Sign up to request clarification or add additional context in comments.

2 Comments

@Cameron, yes it is, since the result of mask >> n is of type int
@JimRhodes, I think the problem definition precludes that.
5

Because there are only a few possibilities, you could just cache them:

// Each index adds another bit from the left, e.g. resultCache[3] == 11100000.
byte[] resultCache = { 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0XF8, 0xFC, 0xFE, 0xFF };

You'd also get an exception instead of a silent error if you accidentally tried to get the value for n > 8.

2 Comments

+1 consolation prize for pointing out a simple & effective approach to many of these types of problems (table lookup) that is easily overlooked, and which all programmers should have in their box-of-tricks. (In this case it's not as good a solution as Henk's, though)
@JasonWilliams Thanks. I voted up Henk's elegant solution before posting this alternative :-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.