Max
Max

Reputation: 4405

Integer to byte with given number of bits set

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?

Upvotes: 5

Views: 158

Answers (2)

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20620

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.

Upvotes: 5

Henk Holterman
Henk Holterman

Reputation: 273264

int n = 3; // 0..8 
int mask = 0xFF00;
byte result  = (byte) (mask >> n);

Upvotes: 11

Related Questions