我只是想知道是否有办法将数字“原位”移位?我已经用谷歌搜索了,我找不到任何与我想做的事情有关的东西。假设我有数字 0b01001101,我想将它向右“原地”移动两次,将所有掉到开头的数字附加。所以它看起来像 0b01010011。c++ 中是否有任何函数可以让我像这样向左或向右移位?
问问题
2307 次
6 回答
1
您想实现旋转移位
这是一个模板化版本,它应该适用于所有类型的整数(包括短裤、字符、整数和无符号/有符号等)。
template<class T>
T rotate_shift_right(T x, int shift)
{
if ((shift > 0) && (shift < (sizeof(x)*8)))
{
x = ((unsigned)x >> shift) | (x << (sizeof(x) * 8 - shift));
}
return x;
}
template<class T>
T rotate_shift_left(T x, int shift)
{
if ((shift > 0) && (shift < (sizeof(x)*8)))
{
x = (x << shift) | (((unsigned)x) >> (sizeof(x) * 8 - shift));
}
return x;
}
于 2011-07-22T17:27:06.753 回答
1
使用汇编指令 ror 并每次都获取进位标志的值应该可以完成这项工作。
int rotate(int x, int n)
{
for(int i = 0; i < n; i++) {
__asm {
ror x, 1 ; rotate and store limit bit in cf
lahf ; get part of flags in ah
and ah, 1 ; get only the cf
shl eax, 31 ; put it at the end
and x, eax ; and store in x
}
}
return x;
}
于 2011-07-22T17:06:32.757 回答
1
自己写一个,我觉得不难。
首先存储右两位,然后进行位移。最后用存储的位填充左两位。
于 2011-07-22T17:08:11.247 回答
0
不,您应该创建自定义的
于 2011-07-22T17:04:26.243 回答
0
这是作为特定于供应商的扩展来实现的。对于 MSVC,您可以使用_rotl8、_rotl16(或_rotr*
用于向右旋转)。不确定 GCC,但您始终可以直接组装并使用rol
or ror
。
于 2011-07-22T17:07:07.737 回答
0
我认为移动它然后将最后一个字节放在开头应该可以。
于 2011-07-22T17:03:25.197 回答