Reputation: 950
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)
Upvotes: 0
Views: 962
Reputation: 213059
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
}
Upvotes: 6