Reputation: 4405
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
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
Reputation: 273264
int n = 3; // 0..8
int mask = 0xFF00;
byte result = (byte) (mask >> n);
Upvotes: 11