B
Brian
Looking around in the class libraries there doesn't appear to be any methods
that do the equivalent of the C runtime lib functions rotr() and rotl(). I
wrote the following but then began to wonder if someone had some generic
methods that would handle differnet word sizes and and signed datatypes.
Doing bit shifting on the signed datatypes kind of surprised me originally.
I thought that if you shifted -2147483643 (0x80000005) by 8 bits right by
doing the folliowing:
-2147483643 >> 16
you would get 0x00058000 but you don't. Instead you get 0xffff8000 becuase
the shift keeps sign extending the thing. So I wrote my own signed int shift
like so:
public static int rotr(int val, int shift)
{
return (val & 0x7fffffff) >> shift | val << (32 - shift) | ((val
< 0) ? 0x01 << (32 - shift - 1) : 0);
}
public static int rotl(int val, int shift)
{
return (val & 0x7fffffff) >> (32 - shift) | val << shift | ((val
< 0) ? 0x01 << (shift - 1) : 0);
}
Where I strip off the high bit and handle it spearately.
Does anyone have any generic methods that do this for all integer sizes both
signed and unsigned? If so I would like to see them as I've spent a little
while trying and can't seem to get it. Or...if someone has a better way I'd
like to know that also...or if I just missed the implementation of these
things in the class lib.
thanks.
that do the equivalent of the C runtime lib functions rotr() and rotl(). I
wrote the following but then began to wonder if someone had some generic
methods that would handle differnet word sizes and and signed datatypes.
Doing bit shifting on the signed datatypes kind of surprised me originally.
I thought that if you shifted -2147483643 (0x80000005) by 8 bits right by
doing the folliowing:
-2147483643 >> 16
you would get 0x00058000 but you don't. Instead you get 0xffff8000 becuase
the shift keeps sign extending the thing. So I wrote my own signed int shift
like so:
public static int rotr(int val, int shift)
{
return (val & 0x7fffffff) >> shift | val << (32 - shift) | ((val
< 0) ? 0x01 << (32 - shift - 1) : 0);
}
public static int rotl(int val, int shift)
{
return (val & 0x7fffffff) >> (32 - shift) | val << shift | ((val
< 0) ? 0x01 << (shift - 1) : 0);
}
Where I strip off the high bit and handle it spearately.
Does anyone have any generic methods that do this for all integer sizes both
signed and unsigned? If so I would like to see them as I've spent a little
while trying and can't seem to get it. Or...if someone has a better way I'd
like to know that also...or if I just missed the implementation of these
things in the class lib.
thanks.