2
uint number = 0x418  in bits : 0000010000011000
uint number1 = 0x8041 in bits: 1000000001000001
uint number2 = 0x1804 in bits: 0001100000000100

I cannot get 0x8041 with

   number >> 4;

or

   (number >> 4) & 0xffff;

How I can get 0x8041 and 0x1804 from 0x418 with shift?

SOLUTION

(number >> nbits) | (number << (16 - nbits))
Ramazan
  • 79
  • 3
  • 13
  • See http://stackoverflow.com/questions/776508/best-practices-for-circular-shift-rotate-operations-in-c for best practices for compiler-friendly rotates that guard against problems when the count is 0 or greater than the type width. Should work equally well in C#. – Peter Cordes Aug 17 '15 at 22:07

2 Answers2

4

C# does not have a bitwise rotate operator - bits shifted past the right end just fall off and vanish. What you can do to solve this is

(number >> nbits) | (number << (32 - nbits))

which will right-rotate a 32-bit unsigned integer by nbits bits.

us2012
  • 16,083
  • 3
  • 46
  • 62
2

What you are describing is typically known as Rotation, not Shifting. In assembly (x86), this is exposed via ROR and ROL instructions.

I'm not aware of a bitwise operator available in C# to do this, but the algorithm is simple enough:

value = value & 0x1 ? (1 << Marshal.SizeOf(value) * 8 - 1) | (value >> 1) : ( value >> 1);
JerKimball
  • 16,584
  • 3
  • 43
  • 55