位旋转功能
Bit Rotation Function
我正在上一个在线类,该类调用,以创建一个称为旋转的函数,该函数将吸收一个对象并旋转其计数位数。这是我当前有
的代码unsigned Rotate(unsigned object, int count)
{
/*Initialize number of bits*/
int numOfBits = CountBits();
if (count < 0)
{
/*Negate count if it was a negative value*/
count = -count;
return (object << count) | (object >> (numOfBits - count));
}
else
return (object >> count) | (object << (numOfBits - count));
}
Countbits的代码为:
const int SHIFT_COUNT = 1; //Set bit shift count to 1
int CountBits()
{
unsigned int uiValue = 1; //Initial value to shift bits
int bitCount; //Variable to store the bit count
/*Left-shift one bit at a time until the value equals zero*/
for (bitCount = 0; uiValue != 0; bitCount++)
uiValue <<= SHIFT_COUNT;
return bitCount;
}
我相信我的代码在前两个测试中旋转1和-1的测试正常工作。但是,当(numofbits -count(负面或大于对象的宽度时,我被标记为转移违规错误:
32位对象被3217位移动(>>(
对象移动(&lt;&lt;(by -3185位
在我的上述代码中应处理这些类型的班次的特定方式?
您不应该移动超过对象的大小。这意味着您应该将传递的数字包裹在限制中] -numofbits;numofbits [,因为-numofbits的旋转 numofbits只是一个no -op。
代码可以变为:
unsigned Rotate(unsigned object, int count)
{
/*Initialize number of bits*/
int numOfBits = CountBits();
count %= numOfBits;
if (count < 0)
...
比对象大小的位移动是未定义的行为。符合程序不得调用不确定的行为。
但是,我们知道,当我们通过对象的大小旋转时,我们最终都会使用原始对象,因此我们只需要通过 count
modulo的 resceue 移动 modulo 对象大小:
#include <limits.h>
unsigned Rotate(unsigned object, int count)
{
static const int max_bits = sizeof object * CHAR_BIT;
count %= max_bits;
if (!count)
/* avoid undefined shift right */
return object;
if (count < 0)
/* force a positive quotient */
count += max_bits;
return (object << count) | (object >> (max_bits - count));
}
int main()
{
unsigned u = 0xFF00;
unsigned v = Rotate(u, 260); /* 256 + 4 */
return v != 0xFF000;
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 与互斥锁相比,旋转锁可以保证上下文切换
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 绘制旋转的三角形
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 位旋转功能
- 我可以将 AVX/SSE 与旋转功能用于 AoS 布局,而不是 SoA 吗?
- 是否有更好的方法(性能提高 /内置功能)获得矩形的旋转角度
- 在OpenGL中实现自己的旋转功能
- 旋转功能C++
- 制作旋转器的功能,每天每分钟创建一个时间戳
- 旋转功能的怪异行为
- 旋转QLabel并保留其功能/样式表
- 使用OpenGL固定功能旋转和平移2D图像