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#?
Related
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.
Function in C
unsigned long int ROTL(unsigned long int x, unsigned long int y)
{
return ((x) << (y&(32 - 1))) | ((x) >> (32 - (y&(32 - 1))));
}
Function in C#
uint ROTL(uint x, uint y)
{
return ((x) << (int)(y & (32 - 1))) | ((x) >> (int)(32- (y & (32 - 1))));
}
above functions do the same work and the same result for small numbers,
but when I pass large numbers the result in C# differ from C.
Is there any problem in casting or in the function itself? Also I try to convert using
Convert.ToInt32()
Assuming unsigned long int translates to a unsigned 64bit integer you want to maybe go with C#s ulong instead of uint.
The main problem there is not the cast to int of the y-parameter, since it only takes the last 5 bits anyway. But when x is of type uint a bitshift with (worst case) 31 places exceeds its limits by far.
Casting and returning it to ulong could do the trick.
ulong ROTL(uint x, uint y)
{
return (((ulong)x) << (int)(y & (32 - 1))) | (((ulong)x) >> (int)(32 - (y & (32 - 1))));
}
Please note, that I did not test this throughly, but only did some boundary tests: https://dotnetfiddle.net/0ETAEL
EDIT: When you expect the results to be bigger than 2^64 (or as Parameter values: ROTL(uint.MaxValue, 31)) you should consider having a look at BigInteger.
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;
I am sure this has to as sweet and plain as butter. But I am not able get it or even find it.
It is related to colours in .net. I have taken a sample code from internet and trying to understand it. It takes a uInt as argument and do something to return a, r, g and b byte values. The method goes as:
private Color UIntToColor(uint color)
{
byte a = (byte)(color >> 24);
byte r = (byte)(color >> 16);
byte g = (byte)(color >> 8);
byte b = (byte)(color >> 0);
return Color.FromArgb(a, r, g, b);
}
so what is >> here. For example,
color = 4278190335 // (blue color)
After processing
a = 255
r = 0
g = 0
b = 255
So can anyone help me to understand this?
It's right-shift operator.
Basically, what it does is that it shifts all bits of the first operand to the right. The second operand specifies how "far" are bits shifted. For example:
uint value = 240; // this can be represented as 11110000
uint shift2 = value >> 2; // shift2 now equals 00111100
uint shift4 = value >> 4; // shift4 now equals 00001111
Good article on the subject is here.
It's in the docs
Right here
So, if you convert your value of 4278190335 to hex (because it's easier to see what's going on) you get 0xFF0000FF
So this line:
byte a = (byte)(color >> 24);
Will shift 0xFF0000FF 24 bits to the right to give you 0x000000FF. If you cast that to a byte, you will truncate off the most significant bits and end up with 0xFF or 255.
So you should be able to figure out what the other 3 lines do.
>> is the shift-right operator.
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.