short packets=BitConverter.ToInt16(data,2);
This line of code, I am using in a application. packets value is coming = 256. Now I want to first right shift 256 using 256>>8 = 1 but in left shift (256<<8) suppose to come 0, but in C#.net it is coming 65536.
Im unable to find the solution. Can Any body help me?
Loading
AlanPosted Aug 29, 2007, 7:15 AM
0xffff is just the hexadecimal representation of the decimal number 65535.
The hex digit 'f' corresponds to '15' in decimal or '1111' in binary.
So 0xffff (the 0x is just a prefix) is equivalent to '11111111 11111111' in binary.
When you AND an int (using the & operator) with 0xffff it masks out the 2 most signifcant bytes and leaves you with the contents of the 2 least signifcant bytes.
When performing bit arithmetic, it's common to use hexadecimal nunbers because you can see immediately what their binary representation is.
Bit arithmetic can be done with both the 'int' and 'long' types (as well as their unsigned counterparts), so there's no need for these particular manipulations when using the 'long' type like there is with 'short'.
subhajit bhaduryPosted Aug 29, 2007, 6:50 AM
AlanPosted Aug 29, 2007, 4:44 AM
The problem is that 'short' operands are automatically promoted to 'int' before the bit shifting operators are applied and an 'int' result is then produced. However, this code should give you the result you want:
short s1 = 256;
short s2 = (short)(s1 << 8 & 0xffff); // 0