0

I want to rotate a byte (very important that it's 8 bits). I know that Windows provides a function, _rotr8 to complete this task. I want to know how I can do this in Linux because I am porting a program there. I ask this because I need to mask bits to 0. An example is this:

#define set_bit(byte,index,value) value ? \ //masking bit to 0 and one require different operators The index is used like so: 01234567 where each number is one bit
        byte |= _rotr8(0x80, index) : \ //mask bit to 1
        byte &= _rotr8(0x7F, index) //mask bit to 0

The second assignment should illustrate the importance of the 8 bit carry rotate (01111111 ror index)

Paul R
  • 208,748
  • 37
  • 389
  • 560
nimsson
  • 930
  • 1
  • 14
  • 27
  • 2
    Related: [How to rotate the bits in a word](http://stackoverflow.com/q/4207546) and [Rotate left/right with number of moves using GCC assembly](http://stackoverflow.com/q/20109970). – jww Nov 30 '14 at 22:07
  • @jww the first one is great! – nimsson Nov 30 '14 at 22:13
  • 1
    here is what has to say about the _rotr8 intrinsic: "Unlike a right-shift operation, when executing a right rotation, the low order bits that fall off the low end are moved into the high order bit positions." Notice there is nothing about including the carry bit in the rotate operation. – user3629249 Dec 01 '14 at 00:19

1 Answers1

6

Although it's fairly simple to rotate a byte, this is a classic example of an XY problem, in that you don't actually need to rotate a byte at all in order to implement your set_bit macro. A simpler and more portable implementation would be:

#define set_bit(byte,index,value) value ? \ 
        byte |= ((uint8_t)0x80 >> index) : \  // mask bit to 1
        byte &= ~((uint8_t)0x80 >> index)     // mask bit to 0

Better yet, since this is 2014 and not 1984, make this an inline function rather than a macro:

inline uint8_t set_bit(uint8_t byte, uint8_t index, uint8_t value)
{
    const uint8_t mask = (uint8_t)0x80 >> index;
    return value ?
        byte | mask :   // mask bit to 1
        byte & ~mask;   // mask bit to 0
}
Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560