c++ - gcc 带进位旋转

标签 c++ c bit-manipulation

我想旋转一个字节(非常重要,它是 8 位)。我知道Windows提供了一个函数_rotr8来完成这个任务。我想知道如何在 Linux 中执行此操作,因为我正在那里移植程序。我问这个是因为我需要将位屏蔽为 0。一个例子是这样的:

#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

第二个赋值应该说明8位进位循环的重要性(01111111 ror index)

最佳答案

虽然旋转一个字节相当简单,但这是 XY problem 的经典示例,因为您实际上不需要旋转一个字节来实现您的 set_bit 宏。一个更简单、更便携的实现是:

#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

更好的是,因为这是 2014 年而不是 1984 年,所以将其设为内联函数而不是宏:

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
}

关于c++ - gcc 带进位旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27218714/

相关文章:

c++ - ASM 堆栈使用

java - java中i &=(i-1) 的含义是什么

algorithm - 转换数组中的第 K 个元素

c - C程序在gcc编译器中跳过了该程序中的循环。

c - 文件指针无缘无故地过期了

c - 需要使用位操作进行一些错误识别

c++ - 使用 C++ REST SDK 将图像从 OpenCV 3 发送到 Cognitive Face API

c++ - 试图替换 C++ 字符串中的字符,完全卡住

c++ - 多个构造函数的内存使用c++

android - 使用不同于 Application.mk 中定义的 STL 编译 android-ndk 模块