按位左旋转功能 [英] Bitwise rotate left function

查看:125
本文介绍了按位左旋转功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个左转函数旋转的整数x n位左

I am trying to implement a rotate left function that rotates an integer x left by n bits


  • 例如:rotateLeft(0x87654321,4)= 0x76543218

  • 法律OPS:〜&放大器; ^ | + LT;< >>

到目前为止,我有这样的:

so far I have this:

int rotateLeft(int x, int n) {
  return ((x << n) | (x >> (32 - n)));
}

我已经实现了对不签订integers..does任何人合作有任何想法,如何解决这一问题?

which I have realized to not work for signed integers..does anyone have any ideas as how to fix this?

所以现在我想:

int rotateLeft(int x, int n) {
  return ((x << n) | ((x >> (32 + (~n + 1))) & 0x0f));
}

和收到错误消息:

错误:测试rotateLeft(-2147483648 [0x80000000的],1 [为0x1])失败...
...给出了15 0xF的。应为1 [为0x1]

ERROR: Test rotateLeft(-2147483648[0x80000000],1[0x1]) failed... ...Gives 15[0xf]. Should be 1[0x1]

推荐答案

有关编译器友好的旋转当前的最佳实践是的这个社区维基Q&安培; A 。从维基百科code不产生铿锵很好ASM或比GCC 5.1以上。

Current best practice for compiler-friendly rotates is this community-wiki Q&A. The code from wikipedia doesn't produce very good asm with clang, or gcc older than 5.1.

有位旋转又名循环移位对维基百科一个很不错的,详细的解释。

There's a very good, detailed explanation of bit rotation a.k.a. circular shift on Wikipedia.

从那里报价:

unsigned int _rotl(const unsigned int value, int shift) {
    if ((shift &= sizeof(value)*8 - 1) == 0)
      return value;
    return (value << shift) | (value >> (sizeof(value)*8 - shift));
}

unsigned int _rotr(const unsigned int value, int shift) {
    if ((shift &= sizeof(value)*8 - 1) == 0)
      return value;
    return (value >> shift) | (value << (sizeof(value)*8 - shift));

在你的情况,因为你没有进入乘法运算符,可以替换 * 8 &LT;&LT; 3

In your case, since you don't have access to the multiplication operator, you can replace *8 with << 3.

修改您还可以删除特定的语句如果语句,你不能使用如果。这是一种优化,但你仍然得到正确的值没有它。

EDIT You can also remove the if statements given your statement that you cannot use if. That is an optimization, but you still get the correct value without it.

请注意,如果你真的打算在签署整数位旋转,旋转后的结果的相互pretation将是依赖于平台。具体来说,这将取决于该平台是否使用补码或的的补。我想不出一个应用程序,它是有意义的旋转有符号整数的位。

Note that, if you really intend to rotate bits on a signed integer, the interpretation of the rotated result will be platform dependent. Specifically, it will depend on whether the platform uses Two's Complement or One's Complement. I can't think of an application where it is meaningful to rotate the bits of a signed integer.

这篇关于按位左旋转功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆