If I have the decimal 12, its representation in binary is 00001100. How do I extract the fifth bit, which in this case is 1? I tried shifting left by 4 and AND-ing with 1 but this is not correct. Can someone tell me what I am doing wrong?
player = low << 4 & 1;
You actually want to obtain 3d bit (starting from the right end):
00001100
^
3d from the right end (bits are zero based)
All you have to do is to get rid of 3 lower bits (100) with a help of >> and check the next bit:
// 1 if 3d bit is set, 0 otherwise
player = (low >> 3) & 1;
Or if you have number 5 - index from the left end and assuming low being byte:
player = (low >> (sizeof(byte) * 8 - 5)) & 1;
You need to left shift the One and & with your variable.
player = (1 << 4) & low;
This will give you the 5th binary digit with trailing zeros.
player = ((1 << 4) & low) >> 4;
This gives the exact 5th binary Digit, removing the Trailing Zeros.
Instead of shifting bits, you can simply use a bitwise AND. As others said, you are looking at the 3rd bit from the right (zero-based), in other words, at the bit that represents 2^3.
player = (low & 8) / 8;
A more generic solution would be
private int GetBit(int number, int bit) => (number & (1 << bit)) / (1 << bit);
Note: This does require casting your decimal to int since & doesn't work with decimals.
Related
I want to calculate powers of two without using Math.Pow because i want to avoid using double. So I need a whole integer value. I thought that I could just use the left shift operator but when my power goes past 30, it gives a negative number for power 31, and 1 for powers larger than 31.
My method looks like
public static long TwoPowX(int power)
{
return (1 << power);
}
Any ideas? Or alternative method?
EDIT:
I need to go as high as power 96 maybe more.
2^96 = 79,228,162,514,264,337,593,543,950,336.
The literal 1 is an int, so the whole expression (1 << power) will also be evaluated as int and overflow before being converted to long. Use 1L instead.
public static long TwoPowX(int power)
{
return (1L << power);
}
What is the maximum power?
Since int consists of 32 bits (31 bits for positive numbers) you get an overflow.
You can use long instead, but then keep in mind the maximum will be a power of 63.
return (long) 1 << power;
I found a solution, instead of long (Int64) which goes to maximum of power 63, I used BigInteger from System.Numerics
public static BigInteger TwoPowX(int power)
{
return ((BigInteger)1 << power);
}
and then usage
BigInteger test = Utility.TwoPowX(96);
yields the correct value for powers greater than 63 (in this example - power of 96)
{79228162514264337593543950336}
I want to change the bits into a 16 bits integer in a certain position but the position of the bits its given from left to right. How to do it ?
Here is an example: I have to change the bits in given position to "1".
int a = 27991; // binary its "01101101 01010111"
int position1 = 12; // this position means i have to change "01101101 0101**0**111"
int position2 = 1; // this position means i have to change "0**1**101101 01010111"
I hope you understood me and someone can help a little.
You can make a mask that has the leftmost bit, and then shift it right positionX times to make the proper mask:
int topBit = 1<<16; // 10000000 00000000
int mask = topBit >> position1;
Now you can use mask to set or to clear the target bit, like this:
int b = a | mask; // Set 12-th bit to 1
int c = a & ~mask; // Set 12-th bit to 0
Console.WriteLine(7 << 4);
Console.WriteLine(7 >> (32 - 4));
For some reason the second method returns 0 instead of 112. But they both should be equal to one another, they both should return 112.
UPDATE:
It's known that (x << n) == (x >> (32 - n)).
Your ideas?
Don't really understand what you expect to see here:
7 << 4 is shifting left (like multiplication) 7 * (2 ^ 4) = 7 * 16 = 112
on another hand
7 >> (32 - 4) is shifting right (like division)7/(2^28), that converted to integer value leads to 0.
The question is why Console.WriteLine peaks integer overload: is cause you act on integer values so expected by CLR result is int.
So result is correct.
(x << n) == (x >> (32 - n))
This is only true if it is a circular shift being performed, which isn't the case in C#. In C# they bits are lost if the are shifted right past the first bit.
//Seven = 00000111
Console.WriteLine(7 >> 1); //00000011
Console.WriteLine(7 >> 2); //00000001
Console.WriteLine(7 >> 3); //00000000
Console.WriteLine(7 >> 4); //00000000
//.
//.
//.
Console.WriteLine(7 >> 28); //00000000
Explained in more detail here:
Is there a way to perform a circular bit shift in C#?
I'm reading some values from a single byte. I'm told in the user-manual that this one byte contains 3 different values. There's a table that looks like this:
I interpret that has meaning precision takes up 3 bits, scale takes up 2 and size takes up 3 for a total of 8 (1 byte).
What I'm not clear on is:
1 - Why is it labeled 7 through 0 instead of 0 through 7 (something to do with significance maybe?)
2 - How do I extract the individual values out of that one byte?
It is customary to number bits in a byte according to their significance: bit x represents 2^x. According to this numbering scheme, the least significant bit gets number zero, the next bit is number one, and so on.
Getting individual bits requires a shift and a masking operation:
var size = (v >> 0) & 7;
var scale = (v >> 3) & 3;
var precision = (v >> 5) & 7;
Shift by the number of bits to the right of the rightmost portion that you need to get (shifting by zero is ignored; I added it for illustration purposes).
Mask with the highest number that fits in the number of bits that you would like to get: 1 for one bit, 3 for two bits, 7 for three bits, 2^x-1 for x bits.
You can do shifts and masks, or you can use the BitArray class: http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
Example with BitVector32:
BitVector32 bv = new BitVector32(0);
var size = BitVector32.CreateSection(7);
var scale = BitVector32.CreateSection(3, size);
var precision = BitVector32.CreateSection(7, scale);
bv[size] = 5;
bv[scale] = 2;
bv[precision] = 4;
LINQPad output:
Potayto, potahto.
You'd use shifts and masks to flatten out the undesired bits, like such:
byte b = something; // b is our byte
int size = b & 0x7;
int scale = (b >> 3) & 0x3;
int position = (b >> 5) & 0x7;
1. Yes, the most significant bit is usually written first. The left-most bit is labeled 7 because when the byte is interpreted as an integer, that bit has value 27 (= 128) when it is set.
This is completely natural and is in fact is exactly the same as how you write decimal numbers (most significant digit first). For example, the number 356 is (3 x 102) + (5 x 101) + (6 x 100).
2. For completion, as mentioned in other answers you can extract the individual values using the bit shift and bitwise-and operators as follows:
int size = x & 7;
int scale = (x >> 3) & 3;
int precision = (x >> 5) & 7;
Important note: this assumes that the individual values are to be interpreted as positive integers. If the values could be negative then this won't work correctly. Given the names of your variables, this is unlikely to be a problem here.
You can do this via bitwise arithmetic:
uint precision = (thatByte & 0xe0) >> 5,
scale = (thatByte & 0x18) >> 3,
size = thatByte & 7;
public int CalcBrackets(int teamCount)
{
int positions = 1;
while (positions < teamCount)
positions *= 2;
return positions;
}
I want the smallest number that is a power of 2 and bigger or equal than teamCount. Is this really the best way to do it? It sure looks horrible :(
If you need to calculate the least power of 2 (not the multiple) smaller then teamCount, then possibly it is the best way. Taking logarithm is a costy operation and can take more time then a simple cycle.
upd
Here is an algorithm (C++) using bitwise operations (http://aggregate.org/MAGIC/, section Next Largest Power of 2)
unsigned int nlpo2(unsigned int x)
{
x--; // comment out to always take the next biggest power of two, even if x is already a power of two
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return (x+1);
}
First, it sets all relevant bits of the number to ones (for example, 0x3ff) and then increments it (0x400) to get the power of two.
That while loop doesn't go over multiples of two, but rather powers of two.
If u really need the multiple just add 1, divide by 2 to get the half part and then multiply back by two:
return ((teamCount+1)/2)*2
so that if it was even then you obtain back the same nuber, while if it was odd, since you add 1 and then divide, you get the next even number.
Smallest multiple
return (teamCount % 2 == 0 ? teamCount : teamCount + 1);
Smallest power, you can take the log. Something like
2 ** (ceil(log_2(teamCount)))
For suitable ceil and log_2 functions. Your technique is fine though.
this way is simple enough:
if (teamCount % 2 == 0)
return teamCount;
else
return (teamCount + 1);
Not bigger smaller and if you mean multiple 2*2*2*2* log aritm best way that is use logaritma function in base 2 and round result to lower base.That is if team count equals 35 log 2 base 35 gives you 5,xxx round it to 5.