An integer with a byte with a given number of bits

I don’t know what to call it, which makes googling search difficult.

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

I think this can be done with:

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

but is there something faster / more pleasant or, preferably, the standard library included in .net?

+5
source share
2 answers
int n = 3; // 0..8 
int mask = 0xFF00;
byte result  = (byte) (mask >> n);
+11
source

Since there are only a few possibilities, you can simply 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 will also get an exception instead of a silent error if you accidentally try to get a value for n> 8.

+5

All Articles