views:

181

answers:

2
+1  Q: 

circular shift c

I have to shift the int one place to the right and return it

In Java i can just return n >> 1;

Is this possible in C?

The method we were given is as follows

// Return n after a right circular 1-bit shift
unsigned int right_circular_shift_1(unsigned int n) {
+9  A: 

C does not have a circular shift, so I guess the exercise is to implement it. The way to do this for a left circular shift is to:

- get the current leftmost bit  and save it
- shift the number leftwards by one
- or the saved bit in at the rightmost bit position

For a right circular shift:

- get the current rightmost bit  and save it
- shift the number rightwards by one
- or the saved bit in at the leftmost bit position
anon
Except that's the wrong way round. The OP wanted a RIGHT circular shift (if he wanted a circular one at all...), i.e. grab bottom bit, shift right, or in previous bottom bit at top.
Julian
@Julian True - I've modified my answer.
anon
The remaining tricky part is to get the position of the leftmost bit. I showed a way, but i then saw it's homework and thus deleted my answer :)
Johannes Schaub - litb
@Johannes I think I would make a small hack and hardcode it for the particular platform I was writing for - particularly for homework :-)
anon
Btw +1 for the nice manual. I think you would make a great teacher :)
Johannes Schaub - litb
+5  A: 

Have you not tried it?

n >> 1

This will work in C (and other C-based languages) as it does in Java (not circular, though).

Johnsyweb
I'd be interested to know why this was downvoted. The OP showed no evidence that they'd tried this before asking whether it were possible; regardless of whether it is circular. Besides they do state, "I have to shift the int one place to the right and return it"
Johnsyweb
@Johnsyweb, I think this deserves an upvote, man!
Johannes Schaub - litb