Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi together!

 

I've searched for a class which rotates a value bitwise! By using only the << or >> Operator, the value will lost bits, because they filled with 0 ! Did someone know how i rotate a value without losing the bits? The value is 32 bits, unsigned!

 

This is an example for C++, but i can't get it work right for C#...

 

unsigned char ror(unsigned char val)

{

int highbit;

if(val & 0x80) // 0x80 is the high bit only

highbit = 1;

else

highbit = 0;

// Left shift (bottom bit becomes 0):

val >>= 1;

// Rotate the high bit onto the bottom:

val |= highbit;

return val;

}

 

Thank you! :D

Posted

Your method is called ror(), which I presume stands for "rotate right", but your code shifts left -- although the highbit part looks good for a right-shift method. It's a little confused... ;) I had a quick go, and came up with this pair:

 

[CS]

class Rotate

{

public static byte RotateLeft(byte val)

{

byte lowbit = (byte) ((val & 0x80) != 0 ? 0x1 : 0x0);

val <<= 1;

val |= lowbit;

return val;

}

 

public static byte RotateRight(byte val)

{

byte highbit = (byte) ((val & 0x1) != 0 ? 0x80 : 0x0);

val >>= 1;

val |= highbit;

return val;

}

}

[/CS]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...