Whatis similar to RotateToLeft in C #?

in java there is a rotatetoleft function that generates the created nunmber

int n; n = Integer.rotateLeft(1, 5); System.out.print(n); 

exit; 32

what looks like this in c #?

+4
source share
2 answers

It looks like you are right after the << operator, but this only performs a left shift; It will not rotate in LSB. To do this, you will need to make a mixture of shifts and OR. For instance:

 static int RotateLeft(int value, int shift) { return (value << shift) | (value >> (32 - shift)); } 

Please note that this will not work correctly if value has its upper bit set due to the expansion of the sign in the right shift. You can fix this by doing arithmetic in uint :

 static int RotateLeft(int value, int shift) { unchecked { uint uvalue = (uint) value; uint uresult = (uvalue << shift) | (uvalue >> 32 - shift); return (int) uresult; } } 
+4
source

I don’t think there is something similar in C # there, I found a similar question here , and the answer offers this implementation: (C language)

 unsigned int _rotl(const unsigned int value, int shift) { if ((shift &= sizeof(value) * 8 - 1) == 0) return value; return (value << shift) | (value >> (sizeof(value)*8 - shift)); } unsigned int _rotr(const unsigned int value, int shift) { if ((shift &= sizeof(value) * 8 - 1) == 0) return value; return (value >> shift) | (value << (sizeof(value)*8 - shift)); } 
0
source

Source: https://habr.com/ru/post/1499808/


All Articles