Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to byte with given number of bits set

Tags:

c#

.net

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?

like image 845
Max Avatar asked Nov 27 '11 17:11

Max


People also ask

How many bits can integers?

1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.


1 Answers

int n = 3; // 0..8 
int mask = 0xFF00;
byte result  = (byte) (mask >> n);
like image 85
Henk Holterman Avatar answered Sep 19 '22 15:09

Henk Holterman