0

I'm looking for algorithm that implements a circular shifting to the left of bit binary number (in c language). The algorithm will act like >> The right slot will be filled not with zeros but with the numbers moved from left.

and for shifting to the right.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Yoyo
  • 9
  • 2
  • 4
  • 6
    What is the question here? What have you already tried? Stack Overflow is a website for discussing specific issues relating to programming; it is not a 'free code service'. If that is what you are looking for, then please look elsewhere. – Delan Azabani Aug 23 '11 at 14:18
  • possible duplicate of [How to rotate the bits in a word](http://stackoverflow.com/questions/4207546/how-to-rotate-the-bits-in-a-word) – zneak Aug 23 '11 at 14:21
  • possible duplicate of http://stackoverflow.com/questions/2943265/circular-shift-c – Nathan Fellman Aug 24 '11 at 04:22

2 Answers2

3

The idea here is to take the upper n bits (for an n bit shift) and or them in to the right of the shifted number.

That should give you a start.

Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
  • While that is true, how does one take the top n bits and or them into the right? – Rudy Velthuis Aug 23 '11 at 15:16
  • Yes, that is obvious. That still doesn't tell people how to mask the bits and by what to shift, etc. – Rudy Velthuis Aug 23 '11 at 18:14
  • @Rudy: you don't need to *mask* anything. The left shift will push zeros from the right. You use the bitwise `or` operator to add in the topmost (length - n) bits. I'm not sure I understand your question. – Nathan Fellman Aug 23 '11 at 19:16
  • OK, I was thinking too complicated. But is it sure that if you shift a negative int right that it doesn't get sign extended, i.e. does it always shift zero bits in from the right? – Rudy Velthuis Aug 23 '11 at 19:34
  • @Rudy: usually, when people deal with bit operations, they're thinking of the number as bit vector, not as a number, signed or otherwise. Just make sure you're using unsigned integers for these operations and avoid the worry. That said, if you must use signed numbers, simply create a mask of n ones and `and` that in to the right-shifted upper bits. – Nathan Fellman Aug 24 '11 at 04:22
1
#define NUM_BITS_IN_INT ((sizeof(int) * 8)

int rotleft(int num, int shift)
{
    return (num << shift) | (num >> (NUM_BITS_IN_INT - shift));
}

int rotright(int num, int shift)
{
    return (num >> shift) | (num << (NUM_BITS_IN_INT - shift);
}
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94